【发布时间】:2023-03-20 15:39:02
【问题描述】:
我正在尝试生成一个线程树,其中每个线程再创建两个,依此类推。到达树的末端(命令行 arg)我需要向后打印分支。
我放弃了使用 malloc 和类似的方法,因为我迷失在错误中,现在我正在使用固定大小的数组。但是我仍然遇到段错误,甚至使用 valgrind 也没有真正的帮助。 理论上我应该只能使用 pthread_create (没有属性)来做到这一点,但我很困惑,你能帮我弄清楚内存泄漏发生在哪里吗? Valgrind 结果主要包括“从 tS 复制”行,但我不明白问题出在哪里。
我真的不是专家,所以我不排除会犯一些愚蠢的错误,谢谢你的耐心。
我附上代码
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <math.h>
int maxDepth;
typedef struct {
int d;
pthread_t *b;
} tS;
void *tF (void *svp) {
tS *sp, s, t[2];
int d, i;
pthread_t branch[maxDepth], mythread;
/*get the struct*/
sp = (tS *) svp;
s = *sp;
/*copy tS values*/
d=s.d;
for (i =0; i< d; i++) {
branch[i]=s.b[i];
}
/*iterate or print*/
if (d < maxDepth) {
for (i=0; i<2; i++) {
t[i].d = d+1;
t[i].b = branch;
t[i].b[d] = pthread_self();
pthread_create(&mythread, NULL, tF, (void *) &t[i]);
}
} else {
printf("Thread tree: ");
for (i =0; i< maxDepth; i++) {
printf("%ld ", branch[i]);
}
putchar('\n');
}
pthread_exit(NULL);
}
int main(int argc, char **argv) {
maxDepth = atoi(argv[1]);
int i;
pthread_t branch[maxDepth];
pthread_t mythread;
tS t[2];
for (i=0; i<2; i++) {
t[i].d = 1;
t[i].b= branch;
t[i].b[0] = pthread_self();
pthread_create(&mythread, NULL, tF, (void *) &t[i]);
}
pthread_exit(NULL);
return 0;
}
【问题讨论】:
标签: c multithreading