Thursday, May 31, 2012

pthreads-2: Creating a detachable thread

In the post "pthread creation" we saw how to create a simple thread and we had used the default attributes for the thread.
One of the default attribute is that the thread is creates always as a joinable i.e. the parent thread has to call pthread_join for the thread to successfully terminate.
On the other hand if we do not want to call pthread_join from the parent, but let the child thread finish and in then inform the parent, then we will have to change the attribute to "detachstate".
If we create a thread in the "detachable" state, then the parent thread need not call pthrea_join, it will just have to wait till the thread exits and informs about it .
The two states supported by POSIX are



To set the attributes to default value we can use



Now to modify the detachstate from joinable we will use the function:



Arguments:



Thus to modify the default initialization we will use



Now we can create a thread using the above attribute variable and we need not call pthread_join on this thread.



Note: hello is the same function we defined in the post "pthread creation"
The full code will look as follows.
detachable_thread.c



Please note that the function "hello" has the statement



This is because the parent is waiting for the child to exit and does not call join to check the child's status.
Now compile it using the options -pthread



Execute it :



Output:



To see the effect of creating a detachable thread, remove the exit from the function "heelo" and the execute the program. We will see that the process goes into an infinite wait as the parent thread keeps waiting for the child thread to call the exit.

0 comments:

Post a Comment