[英]what happen to an unlocked unique_lock when condition_variable::wait() is called?
Here's an sample code on a C++ reference website 这是C ++参考网站上的示例代码
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) {
lck.unlock(); // by curiosity I unlock the lck
cv.wait(lck);
}
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
lck.unlock();
cv.notify_all();
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
go();
for (auto &th : threads)
th.join();
return 0;
}
If I don't unlock the unique_lock before calling wait(), everything works normally. 如果在调用wait()之前未解锁unique_lock,则一切正常。 Like: 喜欢:
thread 9
thread 1
thread 2
thread 3
thread 4
thread 5
thread 6
thread 7
thread 8
thread 0
I've been told that 有人告诉我
At the moment of blocking the thread, the function(
wait()
) automatically calls lck.unlock(), allowing other locked threads to continue. 在阻塞线程时,function(wait()
)自动调用lck.unlock(),从而允许其他锁定的线程继续执行。
So I wonder what if I unlock unique_lock before wait() is called.After I did that, the program behaved weirdly, only one or two threads complete their job(print the "thread X" message), other threads seem to be blocked (by the unique_lock?) forever. 因此,我想知道是否在调用wait()之前解锁unique_lock。在执行此操作之后,程序表现异常,只有一个或两个线程完成其工作(打印“ thread X”消息),而其他线程似乎被阻塞了(唯一地锁定?)。
What happened to those unique_locks? 这些unique_locks发生了什么? Or it's just another undefined behavior of c++ that calling unlock() before wait()? 还是在wait()之前调用unlock()的c ++的另一种未定义行为?
Thanks! 谢谢!
As stated in documentation of std::condition_variable::wait() 如std :: condition_variable :: wait()的文档中所述
Calling this function if lock.mutex() is not locked by the current thread is undefined behavior. 如果lock.mutex()没有被当前线程锁定,则调用此函数是未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.