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

相关推荐
xxxxxxllllllshi21 小时前
Cookie、Session、JWT、SSO,网站与 APP 登录持久化与缓存
java·开发语言·jvm·数据结构·缓存·面试
AI+程序员在路上1 天前
QT6中QToolBox功能与应用
开发语言·qt
用户6605307619621 天前
UFlow:像素级工业零件异常检测 Normalized Flow 方法
算法
aerror1 天前
json转excel xlsx文件
开发语言·python·json
爱吃烤鸡翅的酸菜鱼1 天前
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
java·算法
workflower1 天前
软件工程的知识领域
开发语言·算法·软件工程·个人开发·结对编程
JoannaJuanCV1 天前
error: can‘t find Rust compiler
开发语言·后端·rust
budingxiaomoli1 天前
算法--双指针二
算法
做科研的周师兄1 天前
【机器学习入门】8.2 主成分分析:一文吃透主成分分析(PCA)—— 从原理到核心逻辑
人工智能·算法·决策树·机器学习·流程图
LeeZhao@1 天前
【具身智能】具身机器人VLA算法入门及实战(四):具身智能VLA技术行业进展
人工智能·算法·机器人