Div*_*oML 5 c++ multithreading
以下是来自CPPConference.com的有关 C++ 条件变量的一些代码示例:
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();
}
Run Code Online (Sandbox Code Playgroud)
我不太明白最后在通知另一个线程之前释放锁的部分。
是的
该链接是正确的,如果通知线程拥有锁,则被通知的线程必须阻塞,直到通知线程释放锁。在多核处理器中,这是不必要的延迟。
您的比较有缺陷,因为它缺少细节。涉及两个线程,两个线程同时运行,您的比较忽略了它们。
将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
Run Code Online (Sandbox Code Playgroud)
将notify_one放在解锁后:
notifying thread: notify
notified thread: awaken -> attempt to acquire lock and succeed
Run Code Online (Sandbox Code Playgroud)