多线程范例:在程序执行后,主线程等待全部线程结束后退出。
#include <windows.h> #include <stdlib.h> #include <stdio.h>
DWORD WINAPI ThreadFun(LPVOID); #define THREAD_POOL_SIZE 5
int main(){ HANDLE hThrds[THREAD_POOL_SIZE]; int slot=0; DWORD threadId[THREAD_POOL_SIZE]; int i; DWORD rc;
for(i=0;i<THREAD_POOL_SIZE;i++){ hThrds[i]=CreateThread(NULL, 0, ThreadFun, (LPVOID)i, 0, &threadId[i]); if(hThrds[i]) { printf("Thread %d lanched \n", i); } } rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, true, INFINITE); slot = rc - WAIT_OBJECT_0; if(slot>=0 && slot<THREAD_POOL_SIZE) printf("All thread terminite\n");
for(i=0;i<THREAD_POOL_SIZE;i++){ CloseHandle(hThrds[i]); } return 0; }
DWORD WINAPI ThreadFun(LPVOID n){ int i; for(i=0;i<(int)n;i++){ Sleep(1000); } printf("Thread %d terminate\n", n); return 0; }
|
阅读(3044) | 评论(0) | 转发(0) |