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

相关推荐
blackicexs1 分钟前
第四周第四天
数据结构·c++·算法
TracyCoder1234 分钟前
LeetCode Hot100(46/100)——74. 搜索二维矩阵
算法·leetcode·矩阵
foundbug9996 分钟前
果蝇优化算法(FOA)详解:原理、实现与应用
算法
游乐码6 分钟前
c#递归函数
算法·c#
Pluchon6 分钟前
硅基计划4.0 算法 简单实现B树
java·数据结构·b树·算法·链表
im_AMBER16 分钟前
Leetcode 119 二叉树展开为链表 | 路径总和
数据结构·学习·算法·leetcode·二叉树
Eloudy20 分钟前
SuiteSparse 的 README
人工智能·算法·机器学习·hpc
知无不研38 分钟前
c++的设计模式(常用)
c++·观察者模式·单例模式·设计模式·简单工厂模式
fpcc1 小时前
并行编程实战——CUDA编程的并行前缀和
c++·cuda
maplewen.1 小时前
C++11 返回值优化
开发语言·c++·面试