I am new to threading. Here if I comment pthread_join( thread1, NULL) then in the output sometimes I get
Thread2
Thread1
Thread1
I am not able to understand why Thread1 trace is coming twice and what is the exact functionality of pthread_join.
Also, please refer some tutorial on threading concepts for beginners.
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
If I am getting these results, first of all I would do the following:
1) Instead of below lines,
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
replace it with,
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
pthread_join( thread1, NULL);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
pthread_join( thread2, NULL);
and see what is the result.
2) Inside your thread function, you need to call pthread_exit("Exit"); This is a proper way to exit from the thread function. Do it at the end of function.
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
pthread_exit("Exit");
}
If you are doing it this way, ideally you should not face any problem. In every case, i am assuming you are compiling your program using gcc -D_REENTRANT -o threadex threadex.c -lpthread
This is not the final solution. If it is going well, then we can proceed to next step of starting both the threads at a time.
Please share the feedback after incorporating these changes.
Perhaps the output buffer is not flushing correctly. I've encountered a very similar issue when doing multithreading and piping the output to a file--sometimes output would appear twice. Try adding this line to your main function:
setvbuf(stdout, NULL, _IONBF, 0);
This will force the output buffer to be flushed on each write.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With