c - 在循环内动态分配结构

标签 c multithreading struct

我写了一个简单的程序来使用 pthreads 。

每个线程接收一个指向struct 的指针作为线程数据并打印它。然后我写了一个循环来动态分配 struct,然后在线程创建中使用该点。

问题是,为什么所有线程都收到相同的结构,尽管我已经分配了不同的循环?

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

struct thread_data {
    long thread_id;
    int thread_sum;
};

void *PrintHello(void *threadData)
{

    struct thread_data  *data_input = (struct thread_data *)threadData;

    printf("Hello World! It's me, thread #%ld! ,%d , pointer %d\n", data_input->thread_id, data_input->thread_sum, data_input);
    pthread_exit(NULL);
}


int main(int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];;
    struct thread_data allData[NUM_THREADS];
    int rc;
    long t;
    for (t = 0; t < NUM_THREADS; t++){

        struct thread_data* data = malloc(sizeof(struct thread_data));

        //allData[t].thread_id = t;
        //allData[t].thread_sum = 100;

        //  struct thread_data data;
        data->thread_id = t;
        data->thread_sum = 0;

        printf("In main: creating thread %ld  , %d , %d\n", data->thread_id, data->thread_sum, &data);
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&data);
        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* Last thing that main() should do */
    pthread_exit(NULL);

    return 0;
}

最佳答案

在你的代码中 &data 是类型 struct thread_data ** 替换这个

 rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&data);

由此

 rc = pthread_create(&threads[t], NULL, PrintHello, (void *)data);

此外,您必须为 PrintHello 函数内部(以及在 pthread_exit 之前)分配的每个内存调用 free

关于c - 在循环内动态分配结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30346618/

相关文章:

c - C语言写入txt文件并打印数据

c - 在C中为结构指针数组成员分配地址

python - 在 C 和 Python 中循环

c - 由于数组会退化为指针,为什么我不能应用 const?

c++ - 多线程给出了一些奇怪的结果

Android:从后台线程引发 AlertDialog

python - 在 Python 中,创建和管理线程的首选方式是什么?

c++ - 使用数组和结构的四分卫评级函数表现得很奇怪

c - 接受数组输入,直到输入特定值

c++ - fread 丢失二进制数据