[英]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.