2017-10-31 23 views
-1

私はpthreadsについて学習しています。グローバル変数の値を読み込み、グローバル変数の値を更新する10個のスレッドを作成するプログラムを作成しました。ここでは、プログラムの出力例をいくつか示します。pthreads - グローバル変数の読み込みと書き込み

write()スレッドでは、write()スレッドが作成されるたびに更新されていても、共有変数は2であると常に言いますか?私はそれが変わることが期待されるだろう。

出力:

Write thread - shared variable was 2 and it is now 22 
Read Thread - The shared variable is 2 
Write thread - shared variable was 2 and it is now 9 
Write thread - shared variable was 2 and it is now 12 
Write thread - shared variable was 2 and it is now 37 
Write thread - shared variable was 2 and it is now 43 
Read Thread - The shared variable is 2 
Read Thread - The shared variable is 43 
Read Thread - The shared variable is 43 
Read Thread - The shared variable is 43 

コード:POSIXはすでにこれらの識別子を使用しているため、すべての

#include <stdlib.h> 
#include <pthread.h> 
#include <string.h> 
#include <stdio.h> 


#define NUM_THREADS 5 
int shared_varibale = 2; 

void *read(void *param); 
void *write(void *param); 

int main (int argc, char *argv[]) { 


    int i; 
    time_t t; 
    pthread_t tid[NUM_THREADS]; 

    /* Intializes random number generator */ 
    srand((unsigned) time(&t)); 

    /*Create 5 write threads*/ 
     for(i = 0; i < NUM_THREADS; i++) { 
      pthread_create(&tid[i], NULL, write, &shared_varibale); 
     } 

    /*Create 5 read threads*/ 
    for(i = 0; i < NUM_THREADS; i++) { 
     pthread_create(&tid[i], NULL, read, &shared_varibale); 
    } 

    return 0; 
} 

void *read(void *param) { 
    int *p = (int*)param; 
    printf("The variable is %d\n", *p); 
    pthread_exit(NULL); 
} 


void *write(void *param) { 

    int *p = (int*)param; 
    int rand_varibale = rand() % 50; 
    printf("Write thread - shared variable was %d and it is now %d\n", *p, rand_varibale); 
    *p = rand_varibale; 
    pthread_exit(NULL); 
} 

答えて

1

まず、あなた自身の機能readまたはwriteを呼び出すべきではありません。それをしないと問題を見逃しやすいので、すべての関数呼び出しにもエラーチェックを追加する必要があります。

例では同期がないため、データ競合が発生しています。とりわけ、これは、スレッドが古い値を参照する可能性があることを意味します。そして、あなたはスレッドの実行にいかなる命令も課しません。あなたのハードウェアがそれほど並列性をサポートしているのであれば、printfコール(1つを除いてすべてをブロックする)まで、すべてのスレッドが実行される可能性があります。共有変数はprintfコールの後にのみ書き込まれるため、表示される結果が得られます。

関連する問題