我正在阅读this std::condition_variable
示例:
#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();
}
让我们专注于开始:std::thread worker(worker_thread);
在这里,我们开始工作,它将立即锁定互斥锁:std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
然后,将互斥锁锁定在main上以更改ready
的值{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
但是我们怎么可能到达ready=true
行呢? mutext m
从工作线程中被阻止,因此std::lock_guard<std::mutex> lk(m);
行将等待直到互斥体m
解锁。据我了解,当互斥锁被锁定并且我们尝试锁定它时,我们将等待直到其被解锁。但是,它永远不会被解锁,因为工作线程正在等待,因此不会释放它。
最佳答案
在您附加的链接中,请注意以下内容
The wait operations atomically release the mutex and suspend the execution of the thread.
因此线
cv.wait(lk, []{return ready;});
释放互斥锁并中止线程的执行,直到通知了条件变量,超时到期(使用wit_for()
)或发生虚假唤醒,因此唤醒了线程,并且原子性地重新获取了互斥锁
关于c++ - std::condition_variable和std::mutex到底如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63096725/