gpt4 book ai didi

c++ - 如何确保在 notify_one 之前调用 wait_for

转载 作者:行者123 更新时间:2023-11-28 01:54:46 27 4
gpt4 key购买 nike

条件变量的典型用法如下所示(参见下面的代码):http://en.cppreference.com/w/cpp/thread/condition_variable .

但是,似乎主线程可能会在工作线程调用 wait 之前调用 notify_one,这将导致死锁。我错了吗?如果不是,通常的解决方法是什么?

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});

// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";

// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";

// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
}

int main()
{
std::thread worker(worker_thread);

data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();

// wait for the worker
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';

worker.join();
}

最佳答案

注意 definition of wait使用条件(您应该使用的唯一等待):

while (!pred()) {
wait(lock);
}

如果 notify 已经触发,则意味着条件已经为真(在信号线程中的 notify_one 之前排序)。因此,当接收方获取互斥量并查看 pred() 时,它将为真并继续进行。

关于c++ - 如何确保在 notify_one 之前调用 wait_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594472/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com