下面是有关C++条件变量的CPPConference.com代码示例
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();
}在通知另一个线程之前,我不太理解锁被释放的结尾部分。
发布于 2019-03-14 03:38:25
你的比较是有缺陷的,因为它缺少细节。涉及两个线程,两个线程同时运行,您的比较忽略了这两个线程。
将notify_one放在解锁之前:
notifying thread: notify -> eventually release lock
notified thread: awaken -> attempt to acquire lock and fail -> block until lock available -> acquire lock after notifying thread releases it解锁后放置notify_one:
notifying thread: notify
notified thread: awaken -> attempt to acquire lock and succeedhttps://stackoverflow.com/questions/55154462
复制相似问题