gpt4 book ai didi

c++ - 一个pthread程序在收到条件信号后无法跳出循环

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:00 25 4
gpt4 key购买 nike

这是一个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);
}

最佳答案

线程 1 和 2 可能在线程 3 甚至开始等待条件变量之前就已完成。

这意味着它永远不会收到信号。

首先启动线程 3。在尝试启动 1 和 2 之前,确保它已经达到并正在等待条件。

你真正想要的是 counted semaphore (类似于条件变量,但它会记录 signal() 和 wait() 调用的次数)。如果它的信号多于等待,则线程不会停止。

关于c++ - 一个pthread程序在收到条件信号后无法跳出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8946956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com