#include<stdio.h> #include<unistd.h> #include<pthread.h> void * task(void * param) { sleep(50); 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; } //pthread_join(tid, NULL); printf("创建主线程\n"); pthread_exit(NULL); return 0; }
上面的代码在linux下执行,运行结果为:
创建主线程
hello
运行现象: 没有指定去等待子线程,主线程也会等待子线程执行完毕后,才会最后结束程序.
而windows下,如果不指定等待子线程,则主线程结束后就会马上结束程序.
#include <iostream> #include "windows.h" #include "stdlib.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; return 0; }
执行结果:
主线程执行完毕