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

相关推荐
kylezhao20194 分钟前
C# 中实现自定义的窗口最大化、最小化和关闭按钮
开发语言·c#
阿崽meitoufa8 分钟前
JVM虚拟机:垃圾收集算法
java·jvm·算法
一苓二肆11 分钟前
PUMA机械臂matlab仿真正逆解与路径规划
开发语言·matlab
练习时长一年12 分钟前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
Frank_refuel15 分钟前
C++之继承
开发语言·c++
七号驿栈23 分钟前
07_汽车信息安全算法在线验证工具(测试报告)
算法
sunfove36 分钟前
Python 自动化实战:从识图点击、模拟真人轨迹到封装 EXE 全流程教学
开发语言·python·自动化
傻啦嘿哟37 分钟前
Python网页自动化操作全攻略:从入门到实战
开发语言·python·自动化
啦哈拉哈40 分钟前
【Python】知识点零碎学习4
python·学习·算法
哪有时间简史42 分钟前
C++程序设计
c++