2016-03-21 12 views
0

後で複数の引数を送信する必要があるため、スレッドIDを構造体に送信しようとしています。 data-> arg1 = tを実行してデータを送信しようとすると、PrintHello関数にスレッドIDが格納されます。値を取得する必要はありません。もし私が一緒に私の構造体を取り出して、それだけでプログラムが期待どおりに動作している以上のtを送信します。なぜ誰がこのことが分かるのでしょうか?複数の引数を指定してpthreadを送信する

#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <sys/types.h> 
#include <sys/wait.h> 
#include <errno.h>  
#include <strings.h>  
#include <pthread.h>  

#define NUM_THREADS  5 

void *PrintHello(void *threadid) 
{ 
    struct data *someData = threadid; 
    long threadsID = someData->arg1; 
    sleep(2); 
    printf("Thread %ld\n", threadsID); 
    pthread_exit(NULL); 
} 

int main (int argc, char *argv[]) 
{ 
    pthread_t threads[NUM_THREADS]; 
    pthread_attr_t attr; 
    struct myStruct data; 
    long t; 
    void *status; 

    for(t=0; t<NUM_THREADS; t++){ 
    data.arg1 = t; 
    pthread_create(&threads[t], &attr, PrintHello, (void *)&data);   
    } 

    pthread_attr_destroy(&attr); 
    for (t=0; t < NUM_THREADS; t++) { 
     pthread_join(threads[t], &status); 

    } 
    pthread_exit(NULL); 
} 

構造体を別のヘッダファイルに宣言しました。

答えて

0

スレッドがデータを読み取る前に構造が更新される可能性があるからです。 スレッドごとに別々の構造を割り当てる必要があります。

これを試してみてください:

int main (int argc, char *argv[]) 
{ 
    pthread_t threads[NUM_THREADS]; 
    pthread_attr_t attr; 
    struct myStruct data[NUM_THREADS]; 
    long t; 
    void *status; 

    for(t=0; t<NUM_THREADS; t++){ 
    data[t].arg1 = t; 
    pthread_create(&threads[t], &attr, PrintHello, &data[t]);   
    } 

    pthread_attr_destroy(&attr); 
    for (t=0; t < NUM_THREADS; t++) { 
     pthread_join(threads[t], &status); 

    } 
    pthread_exit(NULL); 
} 
関連する問題