C++ 线程管理

C++ 线程管理

#include 
#include 
#include 
#include 

std::mutex mtx;
std::condition_variable cv;
bool flag = false;

void workerThread() {
    std::cout << "workerThread" << std::endl;
    std::unique_lock<std::mutex> lock(mtx);
    std::cout << "wait" << std::endl;
    cv.wait(lock, []() { return flag; }); // 等待条件满足
    std::cout << "Worker thread is awake!" << std::endl;
}

int main() {
    std::cout << "start" << std::endl;
    std::thread t(workerThread);

    std::this_thread::sleep_for(std::chrono::seconds(2));

    {	// ***释放锁***
        std::lock_guard<std::mutex> lock(mtx);
        flag = true;
    }
    cv.notify_one(); // 通知条件满足 notify_all()
    std::cout << "join" << std::endl;

    t.join();
    std::cout << "finish" << std::endl;

    return 0;
}

运行结果:

start
workerThread
wait
join
Worker thread is awake!
finish

你可能感兴趣的:(thread,c++,开发语言,Thread)