条件変数を使用して2つのスレッド間の同期を作成する単純なプログラムを作成しました。解決策が見つからないような奇妙な出力が表示されます。
プログラムが行うことは、ジェネレータスレッドで、1000個のランダムな整数を生成し、それらが完全な平方であるかどうかを確認することです。数値が完全な平方である場合、数値の平方根を出力するモニタースレッドに信号を送ります。
私が抱えている問題は、ジェネレーターが信号を送ったときにモニターが平方根を出力しないため、ある種の競合状態である可能性があります。
奇妙な部分は、変数が変更されるたびにステップスルーするgdb bでデバッグis_square
すると、問題が存在しないことです。
任意の洞察をいただければ幸いです。私はそれが私のミューテックスまたは条件の配置に関係していると感じています。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#include <time.h>
int square_root;
int is_square = 0;
int done = 0;
int count = 0; //used to count how many perfect squares generator_func finds
int count1 = 0; //used to compare how many responses monitor makes to signal
pthread_mutex_t mutex;
pthread_cond_t mon;
void* generator_func(void* args){
srand(time(NULL));
int i, temp, sq;
for(i = 0; i<1000; i++){
temp = rand() % 10000;
sq = sqrt((double)temp);
if((pow(sq,2)) == temp){
pthread_mutex_lock(&mutex);
count++;
square_root = sq;
is_square = 1;
fprintf(stderr, "Square root of %d is", temp);
pthread_cond_signal(&mon);
pthread_mutex_unlock(&mutex);
}
}
pthread_mutex_lock(&mutex);
done = 1;
is_square = -1;
pthread_cond_signal(&mon);
pthread_mutex_unlock(&mutex);
}
main(){
pthread_t generator; //declare thread
pthread_mutex_init(&mutex, NULL); //initialize mutex
pthread_cond_init(&mon, NULL); //initialize condition variable
pthread_create(&generator, NULL, generator_func, NULL); //create thread
//monitor
while(done != 1){
pthread_mutex_lock(&mutex);
while(is_square == 0){
pthread_cond_wait(&mon, &mutex);
}
if(is_square == 1 && done != 1){
count1++;
fprintf(stderr, " %d\n", square_root);
is_square = 0;
}
pthread_mutex_unlock(&mutex);
}
pthread_join(generator, NULL);
printf("%d %d\n", count, count1); //shows inconsistency between generator and monitor
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&mon);
}