pthread_ Introduction and application of join function



pthread_join function introduction:

The function pthread_join is used to wait for the end of a thread, synchronous operation between threads. Header file: #include < pthread.h>

Int pthread_join(pthread_t thread, void **retval);

description: the pthread_join() function blocks and waits for the thread specified by the thread to terminate. When the function returns, the resource being held by the waiting thread is reclaimed. If the thread has ended, the function returns immediately. And the thread specified must be Joinable.

argument: thread: thread identifier, or thread ID, identifies a unique thread. Retval: User-defined pointer to store the return value of the waiting thread.

return value: 0 for success. Failed and an error number is returned.

.

1, example code:

#include <pthread.h>
   #include <stdlib.h>
   #include <unistd.h>
   #include <stdio.h>
 void *thread_function(void *arg) {
  int i;
  for ( i=0; i<8; i++) {
    printf("Thread working...! %d \n",i);
    sleep(1);
  }
  return NULL;
}
int main(void) {
  pthread_t mythread;
  
  if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
    printf("error creating thread.");
    abort();
  }
  if ( pthread_join ( mythread, NULL ) ) {
    printf("error join thread.");
    abort();
  }
  printf("thread done! \n");
  exit(0);
}

.

O
0 GCC thread.c-o thread.o-pthread

.

./thread. O command execution.

4, the running effect is as follows:



Read More: