来看一段代码:
cpp
void task1(mutex &m) {
cout << "thread 1 init..." << endl;
{
std::unique_lock<mutex> lock(m);
cout << "thread 1 getLock" << endl;
sleep(5);
}
cout << "thread 1 freeLock" << endl;
cout << "thread 1 exit..." << endl;
}
void task2(mutex &m) {
cout << "thread 2 init..." << endl;
{
std::unique_lock<mutex> lock(m);
cout << "thread 2 getLock" << endl;
}
cout << "thread 2 freeLock" << endl;
cout << "thread 2 exit..." << endl;
}
int main() {
mutex m;
jthread t1(task1, std::ref(m));
sleep(1);
jthread t2(task2, std::ref(m));
}
代码的输出:
cpp
thread 1 init...
thread 1 getLock
thread 2 init...
thread 1 freeLock
thread 1 exit...
thread 2 getLock
thread 2 freeLock
thread 2 exit...
可以看出:线程在sleep的时候是不会释放锁的