pthread_join()是否允许在调用线程上继续执行?

Pet*_*uza 4 c c++ multithreading pthreads

编辑: 我错误地假设线程在pthread_join实际开始运行时开始运行pthread_create.


我正在学习使用Posix线程,我已经读过:
pthread_join() - wait for thread termination

因此,在代码示例中,在两个启动线程结束之前,不会到达main的exit(0).
但是在第一次调用pthread_join()之后,main继续执行,因为第二次调用pthread_join()实际上运行了,并且打印了两者之间的消息.
那怎么回事?当两个线程都没有完成时,main是否继续执行?或者不是吗?
我知道这不是一种可靠的测试方法,但无论循环有多长,第二条测试消息总是在两个线程完成后打印出来.(至少在我尝试的机器上)

void *print_message_function( void *ptr )
{
    char *message = (char *) ptr;
    for( int a = 0; a < 1000; ++a )
        printf( "%s - %i\n", message, a );
    return NULL;
}
//
int main( int argc, char *argv[] )
{
    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);
    printf( "Let's see when is this printed...\n" );
    pthread_join( thread2, NULL); 
    printf( "And this one?...\n" );
    //
    printf("Thread 1 returns: %d\n",iret1);
    printf("Thread 2 returns: %d\n",iret2);
    exit(0);
}

cni*_*tar 6

该函数pthread_join等待线程完成或者如果线程已经完成则立即返回.

所以在你的情况下

pthread_join( thread1, NULL); /* Start waiting for thread1. */
printf( "Let's see when is this printed...\n" ); /* Done waiting for thread1. */

pthread_join( thread2, NULL); /* Start waiting for thread2. */
printf( "And this one?...\n" ); /* Done waiting for thread2. */
Run Code Online (Sandbox Code Playgroud)

但是在第一次调用pthread_join()之后,main继续执行,因为第二次调用pthread_join()实际上运行了,并且打印了两者之间的消息.

假.pthread_join等待除非thread1已经完成.