连续两次调用 pthread_join()。第二次调用是否应该在第一个线程终止之前才开始?

Two consecutive calls to pthread_join(). Should the second call not even start until the first thread terminates?

这是代码(改编自www.cs.cmu.edu):

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

 void *print_message_function( void *ptr );
 main()
 {
      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("1\n");
      pthread_join( thread2, NULL);

      printf("Thread 1 returns: %d\n",iret1);
      printf("Thread 2 returns: %d\n",iret2);
      exit(0);
 }

 void *print_message_function( void *ptr )
 {
      char *message;
      message = (char *) ptr;
      printf("%s \n", message);
      sleep(5);
 }

输出为:

 Thread 1 
 Thread 2 
 1
 Thread 1 returns: 0
 Thread 2 returns: 0

前两行是即时显示的。暂停后,显示最后三行。 我认为 pthread_join(thread1, NULL) 会等到 thread1 完成,所以在第一行显示后应该有一个暂停,输出应该是:

 Thread 1 
 1
 Thread 2 
 Thread 1 returns: 0
 Thread 2 returns: 0

为什么?因为 pthread_join 的手册页说:"The pthread_join() function waits for the thread specified by thread to terminate." 如何解释输出?我缺少一些简单的东西。

I thought that pthread_join(thread1, NULL) would have waited until thread1 was completed

以上正确;会的。

so there should have been a pause after the display of the first line

这部分没有跟进。您启动了两个线程 运行,因此两个线程彼此独立执行 (a.k.a."in parallel with"),并且独立于主线程正在执行的操作。这意味着两个线程将立即打印出它们的 "Thread X" 行,然后两个线程将等待 5 秒再退出。同时,主线程将等待线程 1 退出大约五秒钟,然后主线程将打印“1”,然后它将等待线程 2 退出(这应该不会花很长时间,因为线程 2 的 5 秒-延迟将与线程 1 的 5 秒延迟大约同时到期)