首页 > 解决方案 > 产生一些线程并在线程工作者函数中执行计算

问题描述

我正在研究这个程序,它产生一些线程并在线程工作函数中执行计算。然后它将结果汇总在一起。我试图完成run_threads函数:1)产生n个调用runMe的线程,它们传递一个指向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 函数中做错了什么?

标签: c

解决方案


你正在做:total += thr_args[j]并且thr_args包含 [0, 1, 2, 3, 4] 所以总和是 10 是正确的。


推荐阅读