简体   繁体   中英

Why pthread_join does not block and wait for the thread to finish?

#include <stdio.h>
#include <pthread.h>

void* thread(void *v) {
    printf("The thread starts now\n");
    //pthread_exit(NULL);
}

int main() {
    int tid1;
    int retValue = 0;
    pthread_create(&tid1, NULL,thread, NULL);

    retValue = pthread_join(tid1, NULL);
    printf("Thread ID: %d, return value: %d\n",tid1, retValue);

    retValue = pthread_join(tid1, NULL);
    printf("Thread ID: %d, return value: %d\n",tid1, retValue);
    return 0;
}

Sometimes the output is:

Thread ID: 1877241856, return value: 3
Thread ID: 1877241856, return value: 3
The thread starts now

Process finished with exit code 0

The question is:

  1. By definition, pthread_join should block, wait for thread to finish executing, and then execute code that follows it. But why in my code, thread runs after the two pthread_join finish?

  2. By definition, pthread_join returns 0 to indicate successful joining, but why the retValue of my code is always 3, whether thread runs before or after the pthread_join function?

There are a number of bugs in this code:

  1. The first argument of pthread_create() should be a pthread_t , not an int . They are quite possibly not the same size, or otherwise interchangeable, so tid1 might not be a valid pthread id.

  2. The thread does not return 0, or any other value for that matter. There is no return statement.

  3. "On success, pthread_join() returns 0; on error, it returns an error number." The thread's return value, if there was one, would be placed into the unused 2nd argument of pthread_join() . What is being treated as the return value is in fact the result of the pthread_join() call itself. Which is an error. Perhaps it is related to #1 above?

In addition to those found by TrentP worst bug of all is

Joining with a thread that has previously been joined results in undefined behavior.

ie calling pthread_join twice on the same thread

retValue = pthread_join(tid1, NULL);
retValue = pthread_join(tid1, NULL);

Is utterly wrong and saying it works if you change tid1 to pthread_t is wrong. The behaviour being undefined means that anything can happen when pthread_join is called the second time - pthread_join can return an error, pthread_join can return success, it can crash, it can hang, it can modify some other parts of memory, it can cause a new thread to be started...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM