【问题标题】:Signal from pthread to main从 pthread 到 main 的信号
【发布时间】:2015-01-11 23:56:41
【问题描述】:
pthread_t thread_id;
while(1) {
   if(counter < 3) {
      // do something
      pthread_create( &thread_id , NULL , handle_me, (void*)arg);
   }
   else {
      // wait for counter to be changed 
      // pthreads will be changing the counter 
      // when changed, go back to beginning of loop 
      counter++;
   }
}

我正在尝试实现以下目标:从pthread 到 main 的信号。 我有什么选择?

计数器在线程中更改时受mutex 保护。

【问题讨论】:

  • 您可能需要condition variable。顺便说一句,如果没有锁定保护counter 的互斥锁,则不应在循环中检查counter
  • 我可以让主线程等待它从线程发出信号吗?为什么我想到我可以从一个线程向另一个线程发出信号。
  • 您的要求充其量是模糊的,大多数人无法理解。您真正想解决什么问题?
  • 我上面的解释正是我想要的。我对使用条件变量有一个误解,但现在一切都清除了。

标签: c pthreads signals


【解决方案1】:

使用条件变量。从增加计数器的线程使用pthread_cond_signalpthread_cond_broadcast。在等待信号的另一个线程中,使用pthread_cond_waitpthread_cond_timedwait

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多