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

相关推荐
小庞在加油10 分钟前
《dlib库中的聚类》算法详解:从原理到实践
c++·算法·机器学习·数据挖掘·聚类
ComputerInBook13 分钟前
C++ 标准模板库算法之 transform 用法
开发语言·c++·算法·transform算法
杰哥技术分享21 分钟前
PHP Yii2 安装SQL Server扩展-MAC M4 Pro芯片
开发语言·php
快下雨了L1 小时前
Lua现学现卖
开发语言·lua
香饽饽~、2 小时前
【第十一篇】SpringBoot缓存技术
java·开发语言·spring boot·后端·缓存·intellij-idea
Devil枫3 小时前
Kotlin扩展函数与属性
开发语言·python·kotlin
菠萝加点糖3 小时前
Kotlin Data包含ByteArray类型
android·开发语言·kotlin
2301_803554524 小时前
c++中类的前置声明
java·开发语言·c++
hn小菜鸡6 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
不想写bug呀7 小时前
多线程案例——单例模式
java·开发语言·单例模式