これは、シグナルを待つ条件変数を設定していてもwhileループから飛び出ることのできないpthreadコードです。条件信号を受信した後にループを飛び越すことができないpthreadプログラム
何か助けていただければ幸いです。
#include <pthread.h>
#include <iostream>
using namespace std;
pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER;
int counter = 0; int WATCHCOUNT = 12 ;int totalCount = 10 ;
int threadsID[3] = {0,1,2};
pthread_cond_t cout_theashold_cv = PTHREAD_COND_INITIALIZER ;
void* watchCount(void *a) ;
void* increaseCount(void *a)
{
for (int i =0; i < totalCount ; ++i)
{
pthread_mutex_lock(&myMutex);
++counter ;
cout << "I am thread " << *((int *)a) << " I increase count to " << counter << endl ;
if (counter == WATCHCOUNT)
{
cout << "I am thread " << *((int *)a) << " I am before send signal with counter as " << counter << endl ;
pthread_cond_signal(&cout_theashold_cv);
}
pthread_mutex_unlock(&myMutex);
}
}
int main()
{
pthread_t threads[3];
pthread_create(&threads[0], NULL, increaseCount, (void *) &(threadsID[0]));
pthread_create(&threads[1], NULL, increaseCount, (void *) &(threadsID[1]));
pthread_create(&threads[2], NULL, watchCount, (void *) &(threadsID[2]));
for (int i = 0 ; i < 3 ; ++i)
{
pthread_join(threads[i], NULL);
}
return 0 ;
}
// wait for cond var
void* watchCount(void *a)
{
pthread_mutex_lock(&myMutex);
cout << "I am thread " << *((int *)a) << " I am watching count " << counter << endl ;
//while (counter <= WATCHCOUNT)
while (counter <= INT_MAX)
{
cout << "I am thread " << *((int *)a) << " before watch count current count is " << counter << endl ;
pthread_cond_wait(&cout_theashold_cv, &myMutex);
break ;
cout << "I am thread " << *((int *)a) << " after watch count current count is " << counter << endl ;
}
cout << "I am thread " << *((int *)a) << " after loop and watch count current count is " << counter << endl ;
pthread_mutex_unlock(&myMutex);
}