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

相关推荐
乌暮1 小时前
少写重复 CRUD:用大白话搞懂 MyBatis-Plus
java·开发语言·spring boot·面试·mybatis
不绝1911 小时前
Lua基础语法入门:注释、变量类型与字符串操作
开发语言·lua
Hhy_11072 小时前
《C++深度解构07》手撕 vector —— 从底层三指针架构到迭代器失效彻底吃透
c语言·开发语言·c++·学习·visual studio
风落青芜2 小时前
链式二叉树的实现与基本操作
c语言·开发语言·数据结构·算法
艾莉丝努力练剑3 小时前
【QT】系统相关:TCP的API介绍
开发语言·前端·c++·人工智能·qt·学习·tcp/ip
青少儿编程课堂3 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中国剩余定理解析
c++·python·算法·bfs·信息学竞赛
wo_jack3 小时前
C++ 入门笔记(十八):list 进阶 —— const 迭代器、operator-> 与 clear 的坑
数据结构·c++·面试·stl·list
wuxianda10304 小时前
Swift 项目用 Xcode 脚手架起步:默认工程结构和依赖组合为什么会被识别成同源
开发语言·xcode·swift·4.3a·appstore审核
ShineWinsu4 小时前
对于Qt:QVBoxLayout常见属性以及方法的解析
开发语言·数据库·c++·qt·gui·客户端·布局管理器
Sarvartha4 小时前
反射综合案例:SQL 语句生成
java·开发语言