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

相关推荐
好悬给我拽开线2 小时前
ZILOT 论文解析
算法
kloc3 小时前
聊天室项目入口网关子服务的实现
linux·c++
饮水桶_T4 小时前
JAVA IO流笔记
开发语言·数据结构·算法
星夜离尘564 小时前
MATLAB 离散数据分箱:半开区间、末端点与计数、加权和、平均
算法·matlab
Pniubi5 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
地平线开发者5 小时前
征程6|用 hrt\_model\_exec 看清 YOLOv5x 的输入、原始输出和后处理
人工智能·算法
csdn_aspnet6 小时前
C++ 3个有序点的方向(Orientation of 3 ordered points)
c++·算法
Felven6 小时前
C. Brr Brrr Patapim
c语言·开发语言
赤生云电竞6 小时前
GPU算力共享平台架构实践:任务分发与资源隔离的关键配置
算法·架构·gpu算力
小七在进步7 小时前
string的使用(2)
c++