首页 文章

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

提问于
浏览
4

edit: 我错误地假设线程开始在 pthread_join 上运行,当它们真正开始在 pthread_create 上运行时 .


我'm learning to use Posix threads, and I'读过:
pthread_join() - wait for thread termination

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

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);
}

4 回答

  • 6

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

  • 3

    函数 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()实际运行,并且打印中间的消息 .

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

  • 2

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

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

  • 3
    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顺序发生,因为打印是在线程上执行的 .

相关问题