Process
Termination
When the main thread completes, all the child threads are terminated and
their resources freed. We can see this demonstrated if we build and run the
code shown in Listing 5.15.
Listing 5.15 Code
to Create a Child Thread
#include <pthread.h> #include <stdio.h>
void*
thread_code( void * param )
{
printf( "In thread code\n" );
}
int
main()
{
pthread_t thread;
pthread_create( &thread, 0, &thread_code, 0 ); printf( "In
main thread\n" );
}
When the application works, we should see a message
printed by both the main and child threads, as shown in Listing 5.16.
Listing 5.16 Output
from Both Original and Child Threads
$
cc -mt t.c
$
./a.out
In
thread code
In
main thread
However, sometimes the application will produce
output only from the main thread, as shown in Listing 5.17.
Listing 5.17 Output
from Only the Original Thread
$
./a.out
In
main thread
The reason for this behavior is that sometimes the main thread
terminates before the child thread has had time to execute. To avoid this
behavior, the main thread needs to call pthread_exit(), which, for the main thread, will wait until all the other threads have
terminated before exiting. This is true, even if the child threads have been
detached. Listing 5.18 shows a version of the code with this change.
Listing 5.18 Main Thread Calls Waits for Child Threads to Complete
#include <pthread.h> #include <stdio.h>
void* thread_code( void * param )
{
printf("In thread code\n");
}
int main()
{
pthread_t thread;
pthread_create( &thread, 0, &thread_code, 0 ); pthread_detach(
thread );
printf( "In main thread\n" ); pthread_exit( 0 );
}
After this change, all the child
threads will print their output before the main thread exits.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.