产生一些线程并在线程工作器函数中执行计算

时间:2019-07-26 10:20:30

标签: c

我正在研究该程序,该程序产生一些线程并在线程工作程序函数中执行计算。然后,它将结果汇总在一起。我试图完成run_threads函数: 1)生成调用runMe的n个线程,这些线程传递一个指向int(int *)的指针,该指针指向从(0到n-1)的连续值

2)等待所有线程完成并收集退出代码(另一个int *转换为void *) 3)从run_threads()返回退出代码的总和 该代码看起来像这样:

#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

int has_run[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void runMe(int *arg) {
  int value = (*arg);
  assert(value >= 0 && value < 5 && "Bad argument passed to 'runMe()!'");

  has_run[value] = 1;

  int *ret = (int*)malloc(sizeof(int));
  *ret = value * value; 

  pthread_exit((void*)ret);
}

int run_threads(int n) {

     pthread_t threads[n];
    int thr_args[n];
    int total = 0;

    for (int i=0; i<n; i++) {
        thr_args[i] = i;
        pthread_create(threads+i, NULL, (void*)runMe, thr_args+i);

    }
    for (int j=0; j<n; j++)
    {

        void *res = NULL;
        pthread_join(threads[j], &res);

        int *ires = res;


        total += thr_args[j];
        free(ires);
    }
    return total;

}

int main (int argc, char **argv) { 

  int sum = run_threads(5);

  int correct = 0;
  for(int i = 0; i < 5; ++i) {
    if(has_run[i]) correct++;
  }

  printf("%d %d", correct, sum);

  return 0;
}

输出应该是5,30 我有5 10 我猜有内存泄漏吗?您能指出我在run_threads函数中做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您正在做:total += thr_args[j]thr_args包含[0、1、2、3、4],因此总和为10是正确的。