2015-05-20 2 views
0

Я написал простую программу для игры с 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; 
} 
+2

Fix вашего недостающего deallocations и собственная путаницы данных и ALLDATA первым. – deviantfan

+0

вы смешиваете адрес '* data' и' * data'. '(void *) & data' является' struct thread_data ** ', и этот указатель тот же, но значение внутри отличается –

ответ

2

на код &data имеет тип struct thread_data ** заменить этот

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

этим

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

также, вы должны вызвать free для каждой выделенной памяти внутри (и как раз перед pthread_exit) функциями PrintHello

0

непосредственно использовать данные

#include <pthread.h>               
#include <stdio.h>                
#include <stdlib.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;                
} 

Будет Ouput:

In main: creating thread 0 , 0 , -273609272 
In main: creating thread 1 , 0 , -273609272 
Hello World! It's me, thread #0! ,0 , pointer 13357072 
In main: creating thread 2 , 0 , -273609272 
In main: creating thread 3 , 0 , -273609272 
In main: creating thread 4 , 0 , -273609272 
Hello World! It's me, thread #2! ,0 , pointer 13357712 
Hello World! It's me, thread #1! ,0 , pointer 13357392 
Hello World! It's me, thread #4! ,0 , pointer 13359632 
Hello World! It's me, thread #3! ,0 , pointer 13358032 
Смежные вопросы