1. 背景
在Linux環境下,主線程以return 0
結束時,程序會在主線程運行完畢后結束。而當主線程以pthread_exit(NULL)
作為返回值時,主線程會等待子線程結束后才會退出程序。本文將詳細探討這兩種方式的區別,并提供相應的代碼示例。
2. 代碼示例
2.1 Ubuntu
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>void* task(void* param) {sleep(5);printf("hello\\n");pthread_exit(NULL);
}int main() {pthread_t tid;pthread_attr_t attr;pthread_attr_init(&attr);int rc = pthread_create(&tid, &attr, task, NULL);if (rc) {printf("線程創建失敗!\\n");return -1;}printf("創建主線程\\n");// Uncomment one of the following lines to observe the difference// pthread_exit(NULL);// return 0;
}
2.2 Windows
#include <iostream>
#include "windows.h"using namespace std;DWORD WINAPI ThreadFun(void* param) {Sleep(5000);cout << "子線程" << endl;return 0;
}int main() {HANDLE h;DWORD ThreadID;h = CreateThread(0, 0, ThreadFun, NULL, 0, &ThreadID);cout << "主線程執行完畢" << endl;// Uncomment the following line to observe the difference// return 0;
}
3. 運行現象
在Linux下,當主線程以pthread_exit(NULL)
結束時,即使沒有使用pthread_join
指定去等待子線程,主線程也會等待子線程執行完畢后,才會結束程序。而當主線程以return 0
結束時,主線程結束后程序也會立即結束。
在Windows下,主線程中使用return 0
時,主線程執行完畢后程序會立即結束。
4. 總結
通過以上示例和現象觀察,我們可以得出結論:
- 在Linux環境下,使用
pthread_exit(NULL)
作為主線程的返回值會使主線程等待所有子線程執行完畢后再結束程序。 - 在Windows環境下,主線程的
return 0
語句會導致程序立即結束,不會等待其他線程的完成。
選擇使用pthread_exit(NULL)
還是return 0
取決于程序的需求,以確保線程的正確執行順序和程序的正常結束。