【发布时间】:2020-09-26 13:45:53
【问题描述】:
是否可以在循环中重复使用条件变量?我试图创建一个线程池,每当轮到线程时,主线程就会使用条件变量发出信号。一开始,线程会等待信号,然后,它会完成它的工作并继续循环直到循环结束。我在下面试过这个
// one of the threads in the thread pool
while(a condition){
pthread_cond_wait(&cond, &lock);
pthread_mutex_lock(&lock);
// job
pthread_mutex_unlock(&lock);
}
// in main thread, whenever a condition happens
// for a specific thread, main thread signals using condition variable
pthread_cond_signal(&cond);
这段代码有什么问题?
【问题讨论】:
-
pthread_cond_wait接受两个参数。 -
谢谢,我忘了写在这里。我加了。
-
问题不是语法问题。执行时出现死锁。
-
我问正是因为这很重要。等待后您正在锁定互斥锁。这没有任何意义。您需要重新阅读条件变量的工作原理。
-
你不应该在等待条件变量之前锁定互斥锁吗?
标签: c multithreading threadpool thread-synchronization