I have written a simple demonstration program so that I can understand the pthread_join()
function.
I know how to use the pthread_condition_wait()
function to allow asynchronous threading but I'm trying to understand how I can do similar work using the pthread_join()
function.
In the program below I pass Thread 1s ID to Thread 2s function. Inside Thread 2s function I call the pthread_join()
function and pass in Thread 1s ID. I expected this to cause Thread 1 to run first and then for Thread 2 to run second, but what I'm getting is that they both run concurrently.
Is this because only one thread can use the pthread_join()
function at a time and that I am already using the pthread_join()
function when I call it from the main thread?
#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:
pthread_join( thread1, NULL);
from themain()
: it leads to a possibility of concurrent joining, which is undefined. The removal should fix the invalid thread identifier issue, too, because thread1 would remain unjoined until the call from thread2. – Lanham