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

相关推荐
老赵的博客8 分钟前
c++ unqiue指针
java·jvm·c++
o0o_-_25 分钟前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
Dxy123931021640 分钟前
python把文件从一个文件复制到另一个文件夹
开发语言·python
程序猿编码1 小时前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
怎么没有名字注册了啊1 小时前
MFC_Install_Create
c++·mfc
酷飞飞1 小时前
Qt Designer与事件处理
开发语言·qt·命令模式
天雪浪子2 小时前
Python入门教程之赋值运算符
开发语言·python
Wadli2 小时前
C++语法 | static静态|单例模式
开发语言·c++·单例模式
他们都不看好你,偏偏你最不争气2 小时前
【iOS】AFNetworking
开发语言·macos·ios·objective-c
纪元A梦2 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans