繁体   English   中英

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

[英]Does or does not pthread_join() allow execution on calling thread to continue?

编辑:我做了错误的假设,即线程开始运行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);
}

函数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. */

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

假。 除非thread1已经完成,否则pthread_join会等待。

pthread_join( thread1, NULL);

主线程在此连接调用上等待,直到thread1完成其工作。 一旦thread1完成执行,主线程将继续前进并执行下一个语句printf

printf( "Let's see when is this printed...\n" );

同样,主线程将在此处等待,直到thread2完成其工作。

pthread_join( thread2, NULL); 

一旦thread2完成其作业,主线程就会向前移动,并执行下一个printf语句。

printf( "And this one?...\n" );

序列将以上述方式工作。可能,这种情况很快发生,你看到的痕迹让它变得混乱。
另外,不使用printf来查看多线程程序的行为可能会产生误导,printf的顺序可能并不总是指示正确的控制流程因为它是基于时间的,并且缓冲区刷新到stdout可能不会以sasme顺序发生,因为打印是在线程上执行的。

pthread_join()不会返回(阻塞调用线程),直到正在连接的线程终止。 如果线程已经终止,则它会立即返回。

在您的测试中,两个线程都会退出,因此您当然会看到从主线程打印的所有消息。 打印第一条消息时,您知道thread1已完成; 打印第二个时,你知道thread2也是完整的。 这可能会在第一次之后很快发生,因为两个线程在大致相同的时间执行相同数量的工作。

如果第一个pthread_join立即返回,则表明第一个线程已经完成执行。 输出是什么样的? 在“让我们看到这个打印时”之后,你看到任何“线程1 - n”输出吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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