我写了一个简单的程序来使用 pthread
s 。
每个线程接收一个指向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/