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

相关推荐
mjhcsp3 分钟前
C++ A* 算法:启发式路径搜索的黄金标准
android·c++·算法
共享家95275 分钟前
Java入门(类和对象)
java·开发语言
习惯就好zz9 分钟前
Qt Quick 系统托盘完整实践
开发语言·qt·qml·系统托盘·system tray·qapplication·qguiapplication
笨笨马甲10 分钟前
Qt集成OpenCV
开发语言·qt
笨笨马甲10 分钟前
Qt 工业机器视觉开发
开发语言·qt
咚为11 分钟前
深入浅出 Rust FFI:从内存安全到二进制兼容
开发语言·安全·rust
仰泳的熊猫19 分钟前
题目2281:蓝桥杯2018年第九届真题-次数差
数据结构·c++·算法·蓝桥杯
-杨豫23 分钟前
JavaScript入门到精通全套资料,以及核心进阶ES6语法,API,js高级等基础知识和实战教程
开发语言·javascript·es6
小灰灰搞电子24 分钟前
Qt 打印输出:printf与qDebug的区别
开发语言·qt
blackicexs24 分钟前
第九周第一天
数据结构·算法