Is it really to call pthread_join in the main thread?

Is the behavior of this code correct?

#include <stdio.h>
#include <pthread.h>

pthread_t mt;

void *start(void *x)
{
    void *y;
    pthread_join(mt, &y);
    printf("joined main thread\n");
    return 0;
}

int main()
{
    pthread_t t;
    mt = pthread_self();
    pthread_create(&t, 0, start, 0);
    pthread_exit(0);
}
+5
source share
3 answers

Yes it is possible. Indeed, this possibility is one of the main reasons for its existence pthread_detach(). From the POSIX docs for pthread_detach()(see man pthread_detach):

   It  has  been suggested that a "detach" function is not necessary; the
   detachstate thread creation attribute is sufficient,  since  a  thread
   need  never  be dynamically detached. However, need arises in at least
   two cases:

    1. In a cancellation handler for a pthread_join() it is nearly essen-
       tial  to  have  a pthread_detach() function in order to detach the
       thread on which pthread_join() was waiting. Without it,  it  would
       be  necessary  to  have  the  handler do another pthread_join() to
       attempt to detach the thread, which would both delay the cancella-
       tion  processing  for an unbounded period and introduce a new call
       to pthread_join(), which might itself need a cancellation handler.
       A dynamic detach is nearly essential in this case.


    2. In  order  to  detach the "initial thread" (as may be desirable in
       processes that set up server threads).

So what you offer is in accordance with the standards.

Edit: Just to confirm that the POSIX descriptionexec() reads:

The start thread in the new process must be connected as if created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE.

+7
source

, (-, , , ), , . pthreads, , , , .

, , , PTHREAD_CREATE_JOINABLE. , .

Codeguru , .

, , - , , fork/vfork , , .

0

, , pthread_exit main.

, POSIX , main . psmears , main , .

- pthread_detach , . pthread_join .

start main:

  • mainmay be interrupted before it startreachespthread_join

A variable access mutex mtshould capture this.

0
source

All Articles