这是一个pthread代码,即使我已经设置了一个条件变量来等待信号,它也不会跳出while循环。
感谢任何帮助。
#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);
}
答案 0 :(得分:1)
线程3和2都可能在线程3开始等待条件变量之前完成。
这意味着它永远不会收到信号。
首先启动线程3。在尝试启动1和2之前,确保它已到达并且正在等待条件。
你真正想要的是counted semaphore(就像一个条件变量,但它保留了signal()和wait()调用次数的计数)。如果它有比等待更多的信号,则线程不会停止。
答案 1 :(得分:1)
您的计划是竞争条件的受害者。有几个问题,但主要问题似乎是:
很多时候,当你调用“watchCount”的第三个线程进入条件wait()时,前两个线程已经传递了调用信号的计数器的值。因此,即使线程开始等待,也会调用一个信号。因此,你的第三个线程永远等待。 如果您将条件更改为信号计数器&gt; = WATCHCOUNT,您可能会有更好的运气