Pthread查询:线程顺序错误
Pthread query: Sequence of threads error
#include<pthread.h>
#include<stdio.h>
int num_threads=3;
int state=0;
pthread_cond_t cond;
pthread_mutex_t mutex;
void* threadA(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 1 || state == 2) pthread_cond_wait(&cond,&mutex);
printf("Thread An");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void* threadB(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 0 || state == 2)pthread_cond_wait(&cond,&mutex);
printf("Thread Bn");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
void* threadC(void* args) {
int i;
for(i=0; i<5; i++){
pthread_mutex_lock(&mutex);
while(state == 1 || state == 0) pthread_cond_wait(&cond,&mutex);
printf("Thread Cnn");
state = (state+1)%num_threads;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t tid[3];
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex,NULL);
pthread_create(&tid[0],NULL,threadA,NULL);
pthread_create(&tid[1],NULL,threadB,NULL);
pthread_create(&tid[2],NULL,threadC,NULL);
return 0;
}
问题:用上面的代码,我想打印threada threadB threadC依次5次。但答案是不确定的。而命令线程的维护,答案不打印5次。请帮助! !正如@mch在评论中提到的,在允许main()
函数返回之前,您需要等待线程完成:
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
现在,在将上面的连接添加到main()
的末尾之后,您的程序通常会挂起。这是因为pthread_cond_signal()
不会唤醒等待该条件变量的所有线程。如果错误的线程被唤醒(例如,线程c发出条件信号,但被通知的线程不是线程a),那么所有线程将等待条件,并且没有人通知该条件。
要解决这个问题,您需要确保所有线程每次都被唤醒,并让每个线程决定自己是否轮到它(由while(state...) pthread_cond_wait(...);
)。要做到这一点,您可以将对pthread_cond_signal()
的调用替换为对pthread_cond_broadcast()
的调用,这将解除当前在该条件下阻塞的所有线程。
相关文章:
- 以相反的顺序打印数组 - 为什么这在C++中是错误的?
- 为什么切换 if else 语句的顺序会导致错误?
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- 如果在 C++ 构造函数中以错误的顺序初始化对象数据,会发生什么类型的错误
- 试图添加两个矢量,但添加顺序错误
- glDrawArrays的意外行为-参数顺序错误会产生所需的图像
- cout 和 cerr 的控制台输出顺序错误
- C 的输出顺序错误
- Doxygen - pdf 中模块的顺序错误
- Win32_PhysicalMedia序列号有时顺序错误
- b树实现中的元素顺序错误
- 模数 - GCC 的操作数顺序错误?或 UB
- OpenGL缩放/平移坐标系或语句顺序错误
- std::normal_distribution<double> 导致 Windows 与 Linux 的顺序错误?
- 在c++中,向量中的数字相乘顺序错误
- 在c++中使用map时输出顺序错误
- H和HPP问题,包含顺序错误
- 重载的强制转换和后增量运算符——顺序错误
- c++中的正向声明VS编译顺序错误,以避免包含递归标头
- Pthread查询:线程顺序错误