Я написал простую программу для игры с pthread
.Динамическое распределение структуры внутри цикла
Каждый поток получает в качестве данных потока указатель на struct
и печатает его. Затем я написал цикл, чтобы динамически выделить struct
s, а затем использовать точку в создании потока.
Проблема: Почему все потоки получают одинаковые stuct
, хотя я выделил разные циклы?
#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;
}
Fix вашего недостающего deallocations и собственная путаницы данных и ALLDATA первым. – deviantfan
вы смешиваете адрес '* data' и' * data'. '(void *) & data' является' struct thread_data ** ', и этот указатель тот же, но значение внутри отличается –