I'm having trouble understanding the pthread_join() function because of the results I am getting.
If pthread_join() is supposed to pause the calling thread until the thread of the given thread id finishes it's job then why does the following code not do Thread 1 work first then do Thread 2 work. They are both happening concurrently.
If I take out the two pthread_join() lines (from main) the program terminates and nothing happens. Does this mean the main thread is the calling process of both join functions and it is the main thread who is waiting for the other two newly created threads to finish?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionCount1();
void *functionCount2(void*);
int main()
{
/*
How to Compile
gcc -c foo
gcc -pthread -o foo foo.o
*/
printf("\n\n");
int rc;
pthread_t thread1, thread2;
/* Create two thread --I took out error checking for clarity*/
pthread_create( &thread1, NULL, &functionCount1, NULL)
pthread_create( &thread2, NULL, &functionCount2, &thread1)
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("\n\n");
exit(0);
}
void *functionCount1()
{
printf("\nFunction 1");
sleep(5);
printf("\nFunction 1");
return(NULL);
}
void *functionCount2(void* argument)
{
//pthread_t* threadID = (pthread_t*) argument;
//pthread_join(*threadID, NULL);
printf("\nFunction 2");
sleep(5);
printf("\nFunction 2");
return(NULL);
}
Output:
Output with sleep
commented out:
Can someone explain why pthread_join is not doing what the documentation leads you to believe?
That is not quite correct:
pthread_join()
is supposed to pause the calling thread, not the calling process. Since you are callingpthread_join()
from the thread running yourmain
function, the other two threads are allowed to proceed concurrently, i.e. the way they do in your example.The reason the code that you commented out does not work is that you are passing a pointer to
pthread_t
, but then you cast it to plainpthread_t
inside the thread running function (i.e.pthread_t*
becomespthread_t
). Fixing this problem should allow your code to produce the results that you expect:In addition, you should remove
pthread_join( thread1, NULL);
from yourmain
function, because the results of multiple simultaneous calls topthread_join()
specifying the same target thread are undefined.