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

C++中Posix线程使用困惑:循环创建线程出现异常竞态条件

问题分析

你的代码核心问题不是竞态条件,而是线程ID的保存和join逻辑错误,导致程序没有正确等待线程执行完毕:

  • 初始化线程数组时,thread1和thread2是未初始化的变量,数组里存的是无效的垃圾值。
  • 使用范围for循环for (auto th : threads)时,th是数组元素的拷贝,pthread_create(&th, ...)修改的是这个临时拷贝的变量,而非原数组中的元素。后续pthread_join操作的还是数组里的无效垃圾值,根本没等待实际创建的线程完成。

这就解释了为什么会出现无输出、counter值异常的情况:程序主线程可能在子线程还没执行完就已经退出,或者join了错误的线程,导致子线程的执行结果无法正常输出。

修复后的代码

把范围for循环改成引用遍历,确保pthread_create能正确修改数组中的线程ID:

#include <cstdio>
#include <cstdlib>
#include <pthread.h>

void *functionC(void*);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;


int main() {
    pthread_t threads[2]; // 直接声明数组,无需提前定义单个变量

    // 使用引用遍历,确保修改数组内的元素
    for (auto& th : threads) {
        if (pthread_create(&th, NULL, &functionC, NULL) != 0)
        {
            printf("Thread Creation Failed");
        }
    }

    for (auto th : threads) {
        pthread_join(th, NULL);
    }

    exit(0);
}

void *functionC(void *) {
    pthread_mutex_lock(&mutex1);

    counter++;
    printf("Counter Value: %d\n", counter);
    pthread_mutex_unlock(&mutex1);

    return NULL;
}
额外说明
  • 原代码中互斥锁的使用是正确的,不存在竞态条件问题,异常现象完全由线程管理逻辑错误导致。
  • 移除循环直接复制代码时,你直接操作了thread1和thread2变量,pthread_create能正确保存线程ID,后续pthread_join也能正确等待线程,所以运行正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:10:25