Thread Creation in Pthread

To create thread using Pthread library, we need to declare a pthread_t variable and then call pthread_create, to construct the thread and execute it, and pthread_join, to terminate the thread. Note that we need to handle the fail cases from pthread_create and pthread_join with if clause.

pthread_t th;

if (pthread_create(&th, NULL, &routine, NULL) != 0)
  perror("Fail to create thread");
if (pthread_join(th, NULL) != 0)
  perror("Fail to join thread");

Note: Treat pthread_t like an opaque type as it could be any type depends on which function it had been called to. Even though it could sometime return the thread’s identity, DO NOT RELY ON THIS BEHAVIOUR. Call syscall(SYS_gettid) in Linux instead.

Multiple Threads

Multiple threads’ creation should be done in a for loop to avoid repetition. Be cautious that pthread_create and pthread_join should not reside in the same loop. Otherwise, we will lose all the multithreading advantages.

int numOfThreads = 5;
pthread_t th[numOfThreads];

for (int i = 0; i < numOfThreads; i++)
  if (pthread_create(th+i, NULL, &routine, NULL) != 0)
    perror("Fail to create thread");

for (int i = 0; i < numOfThreads; i++)
  if (pthread_join(*(th+i), NULL) != 0)
    perror("Fail to join thread");

Routine

See 202112061141#

Thread Detachment

See 202112132306#

Exit

If pthread_exit is used in the main function, the main process will simply be terminated without waiting for the termination of the threads created by it.

Links to this page
#multithreading #pthread