NewToAndroid
NewToAndroid

Reputation: 581

Using pthread_cond_t to signal end of execution

I am using pthread_cond_t to signal the end of execution of child threads to the main thread. Since I'm not synchronizing the access to a shared resource, I wonder what the loop embracing pthread_cond_wait would be? Here's what I have:

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);
}

Would the main thread, by default, wait until thread1 or thread2 send it a signal or would we need some sort of a conditional loop around the wait?

Also, how would the main thread have access to the exit status of the thread that signaled without explicitly calling pthread_join? Or, is there a way to get the thread_id of the thread that signaled so that the main thread may join it to retrieve its exit status?

Upvotes: 0

Views: 645

Answers (1)

user3793679
user3793679

Reputation:

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.

Upvotes: 1

Related Questions