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,
replace it with,
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.
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 -lpthreadThis 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.