pthread_join() unexpected results

1.3k views Asked by At

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:

enter image description here

Output with sleep commented out:

enter image description here

Can someone explain why pthread_join is not doing what the documentation leads you to believe?

1

There are 1 answers

8
Sergey Kalinichenko On BEST ANSWER

if pthread_join() is supposed to pause the calling process until the thread of the given thread id finishes it's job...

That is not quite correct: pthread_join() is supposed to pause the calling thread, not the calling process. Since you are calling pthread_join() from the thread running your main 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 plain pthread_t inside the thread running function (i.e. pthread_t* becomes pthread_t). Fixing this problem should allow your code to produce the results that you expect:

void *functionCount2(void* argument)
{
    pthread_t *threadID = (pthread_t*) argument;
    pthread_join(*threadID, NULL);
    printf("\nFunction 2");
    sleep(5);
    printf("\nFunction 2");
    return(NULL);
}

In addition, you should remove pthread_join( thread1, NULL); from your main function, because the results of multiple simultaneous calls to pthread_join() specifying the same target thread are undefined.