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

相关推荐
charlie1145141913 分钟前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
呜喵王阿尔萨斯10 分钟前
编程中的英语
c语言·c++
糖葫芦君31 分钟前
Policy Gradient【强化学习的数学原理】
算法
likeGhee1 小时前
python缓存装饰器实现方案
开发语言·python·缓存
whoarethenext1 小时前
使用 C++/Faiss 加速海量 MFCC 特征的相似性搜索
开发语言·c++·faiss
项目題供诗1 小时前
黑马python(二十五)
开发语言·python
慌糖1 小时前
RabbitMQ:消息队列的轻量级王者
开发语言·javascript·ecmascript
醇醛酸醚酮酯2 小时前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
jioulongzi2 小时前
记录一次莫名奇妙的跨域502(badgateway)错误
开发语言·python
向阳@向远方2 小时前
第二章 简单程序设计
开发语言·c++·算法