【发布时间】:2019-12-04 16:17:39
【问题描述】:
我正在开发这个程序,它产生一些线程并在线程工作函数中执行计算。然后它将结果汇总在一起。我试图完成 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 函数中做错了什么?
【问题讨论】:
-
我建议你对你的代码做一些rubber duck debugging,尤其是你加入线程并获得结果的循环。
-
至于内存泄漏,如果你忘记了
free分配给malloc的内存,就会发生这种情况。 -
转换为 (void*) 根本不合适。回调的原型必须与将要调用的原型完全兼容。
标签: c