With every thread some resources are associated like stack and thread local storage etc. 

When a thread exits ideally these resources should be reclaimed by process automatically. But that doesn’t happens always. It depends on which mode thread is running. A Thread can run in two modes i.e.

  • Joinable Mode
  • Detached Mode

Joinable Thread & pthread_join()

By default a thread runs in joinable mode. Joinable thread will not release any resource even after the end of thread function, until some other thread calls pthread_join() with its ID.

pthread_join() is a blocking call, it will block the calling thread until the other thread ends.

  • First parameter of pthread_join() is the ID of target thread.
  • Second parameter of pthread_join() is address of (void *) i.e. (void **), it will point to the return value of thread function i.e. pointer to (void *).

pthread_join() will return non zero value in case of error.

Check out the following example of Joinable Thread,

Output:

Detached Thread & pthread_detach()

A Detached thread automatically releases it allocated resources on exit. No other thread needs to join it. But by default all threads are joinable, so to make a thread detached we need to call pthread_detach() with thread id i.e.

Lets see how to use it,

Also, as detached thread automatically release the resources on exit, therefore there is no way to determine its return value of detached thread function.
pthread_detach() will return non zero value in case of error.

Checkout complete example as follows,

Output:

Output can change on your system because both main and thread function are running in parallel.

If main function exits then all other threads will be exited.

To compile the above code use following command,

g++ example.cpp -lpthread

Click Here to Subscribe for more Articles / Tutorials like this.