【问题标题】:Reusing a Conditional Variable in a Loop in C在 C 中的循环中重用条件变量
【发布时间】: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


【解决方案1】:

感谢大家回答这个问题。我收集了您的答案和我在网上找到的资源,并为我自己的问题找到了解决方案。顺序应该是这样的:

// thread1
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
// job
pthread_mutex_unlock(&lock);

// main thread
pthread_mutex_lock(&lock);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多