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

相关推荐
矿渣渣13 分钟前
AFFS2 的 `yaffs_ext_tags` 数据结构详解
数据结构·算法·文件系统·yaffs2
workflower23 分钟前
使用谱聚类将相似度矩阵分为2类
人工智能·深度学习·算法·机器学习·设计模式·软件工程·软件需求
☆平常心☆23 分钟前
UE5通过C++实现TcpSocket连接
c++·ue5
cwywsx33 分钟前
Linux:进程控制2
linux·运维·算法
Bl_a_ck41 分钟前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
编程有点难1 小时前
Python训练打卡Day23
开发语言·python
程序员爱钓鱼1 小时前
跳转语句:break、continue、goto -《Go语言实战指南》
开发语言·后端·golang·go1.19
真的想上岸啊1 小时前
c语言第一个小游戏:贪吃蛇小游戏06
c语言·算法·链表
边跑边掩护1 小时前
LeetCode 648 单词替换题解
算法·leetcode·职场和发展
hardStudy_h1 小时前
C程序的存储空间分配
c语言·开发语言