通过pthread_create传递struct指针的问题

use*_*594 3 c pthreads

在下面的代码中,当我f->msg在main函数中打印时,数据打印正确.但是,如果我传入mystruct*f pthread_create并尝试打印出msg值,我会在receive_data函数的第二行出现分段错误.

typedef struct _mystruct{
    char *msg;
} mystruct;

void *receive_data(void* vptr){
    mystruct *f = (mystruct*)vptr;
    printf("string is %s\n",mystruct->msg);
    return NULL;
}

int main(){
    mystruct *f = malloc(sizeof(mystruct));
    f->msg = malloc(1000);
    f->msg[0] = '\0';
    strcpy(f->msg,"Hello World");
    pthread_t worker;
    printf("[%s]\n",f->msg);
    // attr initialization is not shown
    pthread_create(&worker,&attr,receive_data,&f);
}
Run Code Online (Sandbox Code Playgroud)

未显示pthread的其他初始化代码.

我该如何解决这个问题?

Mat*_*Mat 8

你正在向指针传递指针mystruct.不要那样做.

pthread_create(&worker, &attr, receive_data, f);
Run Code Online (Sandbox Code Playgroud)

足够.f已经是类型了mystruct*.&f是类型的mystruct**.

  • OP的程序几乎肯定会在它有机会打印任何东西之前终止,因为它在'main`结束时运行... (2认同)