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

相关推荐
杨充14 分钟前
05.多用组合和少继承
开发语言·bash
带多刺的玫瑰21 分钟前
Leecode#4刷题之寻找两个正序数组的中位数
java·前端·算法
土司大王30 分钟前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
IvanCodes33 分钟前
RAG 实战教程(三):向量数据库检索算法,KNN、IVF、HNSW 与 Faiss 实战
人工智能·算法·agent
傻啦嘿哟43 分钟前
王者荣耀爬虫:爬取全英雄皮肤数据,用Python做可视化分析
开发语言·爬虫·python
阿无,1 小时前
布隆过滤器
java·算法·哈希算法
AI直播技术杂谈1 小时前
直播画面突然模糊了,排查了三个小时
开发语言·php
徒慕风流1 小时前
激光雷达回波信号滤波与时刻鉴别算法:原理、代码实现与仿真验证
python·算法·激光雷达
菜冻鱼1 小时前
Python-pytorch-数据加载
开发语言·人工智能·pytorch·python·深度学习·机器学习
这料鬼有毒1 小时前
二刷hot100-70.爬楼梯
算法