线程sleep的时候会释放锁吗

来看一段代码:

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的时候是不会释放锁的

相关推荐
Zach_yuan7 分钟前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络
我在人间贩卖青春9 分钟前
C++之this指针
c++·this
云姜.12 分钟前
java多态
java·开发语言·c++
CoderCodingNo21 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳103028 分钟前
C++:红黑树
开发语言·c++
大闲在人32 分钟前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
一切尽在,你来33 分钟前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++
泉-java35 分钟前
第56条:为所有导出的API元素编写文档注释 《Effective Java》
java·开发语言
小熳芋35 分钟前
443. 压缩字符串-python-双指针
算法
Charlie_lll1 小时前
力扣解题-移动零
后端·算法·leetcode