私は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);
}