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
取决于程序的需求,以确保线程的正确执行顺序和程序的正常结束。