Sparun线程在运行期间只要处于活动状态就执行其他操作

问题描述 投票:0回答:1

我下面有一个简单的程序,其中一些长时间运行的进程someFn工作,设置状态,工作设置状态,工作并设置状态。

someFn正在运行时,我希望主线程在someFn的生命周期内查询其设置的状态。

显然,此代码是不正确的,因为在实际加入之前,Tjoinable,并且该程序没有停止。

如何正确地使主线程在T的生命周期内循环并在T终止后立即停止循环?

#include <iostream>
#include <thread>
#include <chrono>

int STATE = 0;
static std::mutex mtx;

void setState(int newState) {
    std::lock_guard<std::mutex> lg(mtx);
    STATE = newState;
}

int getState() {
    std::lock_guard<std::mutex> lg(mtx);
    return STATE;
}


void someFn() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(0);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(1);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(2);
}

int main()
{

    std::thread T(someFn);

    while (T.joinable()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        std::cout << getState() << std::endl;
    }

    T.join();

    return 0;

}

谢谢!

c++ multithreading stdthread
1个回答
1
投票

只有std::thread不能。

但是您可以轻松制作自己的信号。例如:

#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>

int STATE = 0;
static std::mutex mtx;

void setState(int newState) {
    std::lock_guard<std::mutex> lg(mtx);
    STATE = newState;
}

int getState() {
    std::lock_guard<std::mutex> lg(mtx);
    return STATE;
}


void someFn(std::atomic<bool>& isDone) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(0);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(1);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    setState(2);
    isDone.store(true);
}

int main()
{
    std::atomic<bool> isDone{false};
    std::thread T(someFn, isDone);

    while (!isDone.load()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        std::cout << getState() << std::endl;
    }

    T.join();

    return 0;

}

std::atomic不需要互斥或其他同步,因为它已经是线程安全的。

© www.soinside.com 2019 - 2024. All rights reserved.