【问题标题】:different number of thread is created创建不同数量的线程
【发布时间】:2021-11-24 00:33:32
【问题描述】:

我正在学习 pthread,我正在使用 vs 代码来运行 c 代码。 根据 vs 代码文档,我安装了 MSY2S2 MSY 并且它已安装。

当我运行这段代码时:

#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>

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


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<4; i++){
    indexCount[i] = i;
    pthread_create(&tid[i], NULL, bin_finding, &indexCount[i]);
 }
    return 0;
}

当我在最左边的选项中单击运行和调试时,每次都会给出不同的结果。

有时我得到 0 有时 01 有时0123

所以几乎每次运行都是不同的,最常见的是 0。

如果有人,请帮助我。

【问题讨论】:

    标签: c multithreading pthreads hpc


    【解决方案1】:

    您的程序在所有执行线程有机会完成之前退出。

    在第一个循环之后使用第二个循环,其中包含对 pthread_join 的调用,以等待每个线程完全执行:

    for (int i = 0; i < num_of_thread; i++)
        pthread_join(tid[i], NULL);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多