c - 产生一些线程并在线程工作者函数中执行计算
问题描述
我正在研究这个程序,它产生一些线程并在线程工作函数中执行计算。然后它将结果汇总在一起。我试图完成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 函数中做错了什么?
解决方案
你正在做:total += thr_args[j]
并且thr_args
包含 [0, 1, 2, 3, 4] 所以总和是 10 是正确的。
推荐阅读
- python - 如何用列表中的值替换 url 中的值并使用 FOR 循环遍历它们
- node.js - 我应该使用哪个 HTTP 动词来删除 MongoDB 子文档?
- python-3.x - 如何使用混淆矩阵评估 NMF 主题建模?
- c++ - 数组中的 C++ 等号运算符
- git - 将旧分支上的新提交合并到 dev
- google-apps-script - 从表单响应到另一个工作表的最后一行,并且能够在将来覆盖
- javascript - 在 safari ios 上禁用下拉以退出全屏模式
- .htaccess - 如何使用 htaccess 在 url 中使用最终的可选尾随斜杠消除对 txt 扩展的需要
- django - 'float' 和 'NoneType' 的实例之间不支持 Django '>'
- arrays - 如何将独立值绑定到数组中的字符串(Swift)?