【问题标题】:C Thread creation treeC 线程创建树
【发布时间】: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


    【解决方案1】:

    一个问题是

    tS t[2];
    pthread_t  branch[maxDepth];
    

    是局部变量,一旦控制退出函数就会被销毁,因为你在任何地方都没有join

    您将与参数相同的变量传递给pthread_create()

      for (i=0; i<2; i++) {
                t[i].d = d+1;
                t[i].b = branch;  // Here
                t[i].b[d] = pthread_self();
                pthread_create(&mythread, NULL, tF, (void *) &t[i]); //and here
            }
    

    你可以尝试动态分配。

       tS *t = malloc(sizoeof(*t)*2);
       t[i].b = malloc(sizeof(pthread_t)*maxDepth);
    

    【讨论】:

    • 嘿,谢谢。我没有使用 join 因为(作为一种任务)任务没有要求它。现在我尝试添加它,确实段错误消失了。只是一个问题,如果我使用 malloc 选项,我会在哪里释放内存而不弄乱一切?
    猜你喜欢
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多