0

我正在使用 pthread_cond_t 向主线程发出子线程执行结束的信号。由于我没有同步对共享资源的访问,我想知道包含 pthread_cond_wait 的循环是什么?这是我所拥有的:

pthread_mutex_t mutex;
pthread_cond_t cond;

int main(int argc, char *argv[])
{
        pthread_cond_init(&cond, NULL);
        cond = PTHREAD_COND_INITIALIZER;

        pthread_create(&tid1, NULL, func1, NULL);
        pthread_create(&tid2, NULL, func2, NULL);

        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        pthread_mutex_unlock(&mutex);

        //Join the thread that first completes

}

void *func1(void *arg)
{
        ....
        pthread_cond_signal(&cond);
        pthread_exit((void *) 1);
}

void *func2(void *arg)
{
        ....
        pthread_cond_signal(&cond);
        pthread_exit((void *) 1);
}

默认情况下,主线程会等到 thread1 或 thread2 向它发送信号,还是我们需要围绕等待的某种条件循环?

此外,如果没有显式调用 pthread_join,主线程如何访问发出信号的线程的退出状态?或者,有没有办法获取发出信号的线程的 thread_id,以便主线程可以加入它以检索其退出状态?

4

1 回答 1

1

If both threads run to completion before the main thread reaches the pthread_cond_wait(), then it will wait forever. Otherwise, the main thread will wait until one of the other threads signals the condition.

No, you cannot ask the condition who signalled it.

Your pthread condition has no memory; if no thread is waiting on the condition when it is signalled, the signal is not remembered. What matters is the state you manage, protected by the mutex. The pthread condition is simply the mechanism which allows the thread to wait if the state requires it.

So, whatever information you need to pass from the child threads to the parent, the trick is to do that under the mutex. In this case you want to pass the fact that the child has finished. Perhaps a simple bool, so the main thread:

  pthread_mutex_lock(&mutex) ;
  while (!t1_done && !t2_done)
    pthread_cond_wait(&cond, &mutex) ;
  pthread_mutex_unlock(&mutex) ;

And thread the first:

  pthread_mutex_lock(&mutex) ;
  t1_done = true ;
  pthread_cond_signal(&cond) ;
  pthread_mutex_unlock(&mutex) ;

...all pretty straightforward, really.

于 2014-09-06T22:40:48.630 回答