【发布时间】:2015-08-10 07:11:36
【问题描述】:
我需要澄清一下 lock 和 condition_variable 是如何工作的。
在此处的 -slightly modified- 代码中 cplusplusreference
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);
std::this_thread::sleep_for(std::chrono::seconds(1));
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();
}
让我感到困惑的是,如果 worker_thread 已经锁定了互斥锁,主线程如何锁定它。
从this answer我看到是因为cv.wait解锁互斥体。
但现在我对此感到困惑:那么,如果cv.wait 会解锁它,我们为什么还要锁定它呢?
例如,我可以这样做吗?
std::unique_lock<std::mutex> lk(m, std::defer_lock);
所以,我创建了锁对象,因为 cv 需要它,但是我在创建时没有锁定它。
现在有什么不同吗?
在这种情况下,我不明白为什么会收到“运行时错误”here。
【问题讨论】:
标签: c++ c++11 concurrency mutex condition-variable