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

VS Code下MSYS2环境运行pthread多线程C程序输出结果不稳定求助

问题成因
  • 主线程在创建完4个子线程后没有等待子线程执行完成,就直接执行return 0终止了整个进程。进程退出时会强制终止所有还在运行的子线程,输出结果的差异本质是不同运行环境下,CPU调度子线程的顺序和时机不同,只有赶在进程终止前完成打印逻辑的子线程才能输出内容。第一个创建的线程最先被调度的概率最高,所以仅输出0的情况出现最多。
  • 额外影响因素:printf默认采用行缓冲机制,你代码中打印内容没有加换行符\n,打印的内容会先暂存到输出缓冲区,就算子线程执行了printf,如果还没来得及刷新缓冲区进程就退出,内容也不会显示到终端。
解决方法
  • 新增线程等待逻辑:创建完所有子线程后,循环调用pthread_join()函数,阻塞主线程直到对应子线程执行完成后再继续,保证所有子线程都能执行完逻辑再退出进程。
  • 优化打印逻辑:在printf的打印内容末尾添加换行符\n,主动触发缓冲区刷新,确保内容可以立刻输出到终端。
修复后完整代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *bin_finding(void *p){
  int* ptr = (int*)p;
  printf("%d\n", *ptr);
  // printf("%s\n", "hello");
  return NULL;
}

int main(){
  int data_count = 10;
  int num_of_thread = 4;
  int equalDivisionCount = data_count/num_of_thread;
  int excessCount = data_count%num_of_thread;
  int indexCount[num_of_thread];

  int i;
  pthread_t tid[num_of_thread];
  for(i=0; i<num_of_thread; i++){
    indexCount[i] = i;
    pthread_create(&tid[i], NULL, bin_finding, &indexCount[i]);
  }
  for(i=0; i<num_of_thread; i++){
    pthread_join(tid[i], NULL);
  }
  return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 22:48:03