You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

等待已销毁的mutex是否会崩溃?Linux下测试实例解析

销毁互斥锁后执行条件变量等待会导致程序崩溃吗?

不一定会直接崩溃,但这属于未定义行为,结果完全不可预测。

以下是Linux环境下的测试示例,运行后未出现崩溃:

#include <pthread.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 

void* threadLoop() {
    pthread_mutex_lock(&lock); 
    printf("%d %lu Waiting\n", getpid(), pthread_self());
    pthread_cond_wait(&cond, &lock); 
    pthread_mutex_unlock(&lock); 
    printf("%d %lu Return\n", getpid(), pthread_self()); 
    return NULL; 
}    

int main() { 
    printf("%d %lu main\n", getpid(), pthread_self());
    pthread_t tid;
    pthread_create(&tid, NULL, threadLoop, NULL); 
    sleep(1); 

    printf("%d %lu destroy\n", getpid(), pthread_self());
    pthread_mutex_destroy(&lock); 
    sleep(1); 
    printf("%d %lu signal\n", getpid(), pthread_self());
    pthread_cond_signal(&cond); 
    pthread_join(tid, NULL); 
    printf("%d %lu done\n", getpid(), pthread_self());
    return 0; 
}

程序输出:

6332 140377089791808 main
6332 140377086490304 Waiting
6332 140377089791808 destroy
6332 140377089791808 signal
6332 140377086490304 Return
6332 140377089791808 done

关键说明

  • 线程调用pthread_cond_wait时会自动释放持有的互斥锁,所以主线程销毁锁时,线程并没有持有锁。但线程被唤醒后会尝试重新获取这个已经被销毁的互斥锁,这一步属于未定义行为。
  • 本次测试未崩溃只是特定环境下的偶然结果,换用不同的glibc版本、内核版本,或者调整线程调度时机,都可能触发崩溃、死锁或其他异常。
  • POSIX标准明确规定:对已销毁的互斥锁执行任何操作(包括锁定、解锁)都是未定义行为,绝对不能在生产代码中依赖这种不确定的表现。

内容的提问来源于stack exchange,提问作者lucky1928

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 00:47:26