5.2 Creating a new thread

The call pthread_create is used to create a new thread. The following code illustrates an example:

#include <pthread.h> 
 
void task1(void *
{ 
  /* do some important stuff */ 
} 
 
int main(void
{ 
  pthread_t task1Thread; 
  int err; 
 
  err = pthread_create(&task1Thread, NULL, task1, NULL); 
  if (err == 0) 
  { 
    /* now one thread runs task1 */ 
    /* and main gets to do something of its own */ 
    /* when main is done with what it needs to do */ 
    err = pthread_join(task1Thread, NULL); 
    if (err == 0) 
    { 
      /* now two threads become one again! */ 
      /* continue execution as one */ 
    } 
    else 
    { 
      /* report the error of joining */ 
    } 
  } 
  else 
  { 
    /* report the error */ 
  } 
}

This code calls pthread_create to create a new thread to execute task1. As soon as pthread_create returns 0, the new thread (identified by task1Thread) executes task1 in parallel to main.

At this point, the first thread and the new thread execute independently, for the most part. It is as if the two functions, main and task1, execute in parallel. You can see pthread_create(&task1Thread, NULL, task1, NULL) as “call task1 in parallel”.

Most normal threads terminate at some point. In this sample code, we assume there is some more work to do after task1 completes. The call to pthread_join blocks until task1 “returns”. If task1 returns before pthread_join, then pthread_join returns right away.

What is interesting is that errno is not shared by threads of the same process. This is because what we see as an integer is actually a macro. This macro, in return, expands to a function call that returns an address of an integer that is thread specific.