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

相关推荐
星夜离尘562 分钟前
MATLAB阶跃响应怎么量:别把最后一个采样点当成稳态
开发语言·matlab
Jasmine_llq7 分钟前
《P8816 [CSP-J 2022] 上升点列》
数据结构·算法·贪心·排序·二维动态规划 dp·类背包状态转移
Android小码家9 分钟前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle
hetao173383710 分钟前
2026-10-19 hetao1733837 的刷题记录
c++·算法
夏虫不可与之言冰13 分钟前
第三课 点亮 LED 与定时器非阻塞闪烁
c语言·c++·vscode·单片机·嵌入式硬件·物联网
云水初15 分钟前
【agent篇】RAG Agent避坑指南(附高级RAG Agent汇总)
开发语言·笔记·python·学习·langchain·agent·rag
Littlehero_12117 分钟前
QT自定义控件之水泥厂组态(源码开源)
开发语言·qt
辛苦才能26 分钟前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
m0_6399069429 分钟前
HashMap:哈希扰动、扩容源码、红黑树转换、并发问题
java·算法·哈希算法
miller-tsunami37 分钟前
STL简介&string相关知识点
开发语言·c++·string