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

相关推荐
森G几秒前
71、打包发布---------打包发布
c++·qt
小冷爱读书1 分钟前
C++ 单例四种实现完整演进逻辑
开发语言·c++·c++学习
bubiyoushang88811 分钟前
电力线信道“五类噪声”仿真MATLAB
开发语言·matlab
cici1587412 分钟前
彩色图像模糊增强(Fuzzy Enhancement)MATLAB 实现
开发语言·算法·matlab
kaikaile199512 分钟前
图像稀疏化分解 + 压缩感知(CS)重建 MATLAB
开发语言·计算机视觉·matlab
yugi98783814 分钟前
PNCC(Power-Normalized Cepstral Coefficients)— MATLAB 实现
开发语言·人工智能·matlab
大黄说说16 分钟前
C++20 协程从入门到网络服务
开发语言
你是个什么橙18 分钟前
Python入门学习2:Python 基础语法全解析——从代码结构到输入输出
开发语言·python·学习
小白学大数据20 分钟前
Python + 大模型行业资讯自动化摘要流水线完整工程实现方案
开发语言·python·自动化
宝贝儿好21 分钟前
【LLM】第二章:HuggingFace入门学习
人工智能·深度学习·神经网络·学习·算法·自然语言处理