1 #include <stdio.h>
2 #include <windows.h>
3
4 // 线程函数
5 DWORD WINAPI ThreadProc(LPVOID lpParam) 6 { 7 int i = 0; 8 while(i < 20) 9 { 10 printf(" I am from a thread, count = %d \n", i++); 11 } 12 return 0; 13 } 14
15 int main(int argc, char* argv[]) 16 { 17 HANDLE hThread; 18 DWORD dwThreadId; 19
20 // 创建一个线程
21 hThread = ::CreateThread ( 22 NULL, // 默认安全属性
23 NULL, // 默认堆栈大小
24 ThreadProc, // 线程入口地址(执行线程的函数)
25 NULL, // 传给函数的参数
26 0, // 指定线程立即运行
27 &dwThreadId); // 返回线程的ID号
28 printf(" Now another thread has been created. ID = %d \n", dwThreadId); 29
30 // 等待新线程运行结束
31 ::WaitForSingleObject (hThread, INFINITE); 32 ::CloseHandle (hThread); 33 return 0; 34 }
1 #include <stdio.h>
2 #include <windows.h>
3
4 DWORD WINAPI ThreadIdle(LPVOID lpParam) 5 { 6 int i = 0; 7 while(i++<10) 8 printf("Idle Thread is running \n"); 9
10 return 0; 11 } 12
13 DWORD WINAPI ThreadNormal(LPVOID lpParam) 14 { 15 int i = 0; 16 while(i++<10) 17 printf(" Normal Thread is running \n"); 18
19 return 0; 20 } 21 int main(int argc, char* argv[]) 22 { 23 DWORD dwThreadID; 24 HANDLE h[2]; 25
26 // 创建一个优先级为Idle的线程
27 h[0] = ::CreateThread(NULL, 0, ThreadIdle, NULL, 28 CREATE_SUSPENDED, &dwThreadID); 29 ::SetThreadPriority(h[0], THREAD_PRIORITY_IDLE); 30 ::ResumeThread(h[0]); 31
32 // 创建一个优先级为Normal的线程
33 h[1] = ::CreateThread(NULL, 0, ThreadNormal, NULL, 34 0, &dwThreadID); 35
36 // 等待两个线程内核对象都变成受信状态
37 ::WaitForMultipleObjects( 38 2, // DWORD nCount 要等待的内核对象的数量
39 h, // CONST HANDLE *lpHandles 句柄数组
40 TRUE, // BOOL bWaitAll 指定是否等待所有内核对象变成受信状态
41 INFINITE); // DWORD dwMilliseconds 要等待的时间
42
43 ::CloseHandle(h[0]); 44 ::CloseHandle(h[1]); 45
46 return 0; 47 } 48
49 /*
50 HANDLE h[2]; 51 h[0] = hThread1; 52 h[1] = hThread2; 53 DWORD dw = ::WaitForMultipleObjects(2, h, FALSE, 5000); 54 switch(dw) 55 { 56 case WAIT_FAILED: 57 // 调用WaitForMultipleObjects函数失败(句柄无效?) 58 break; 59 case WAIT_TIMEOUT: 60 // 在5秒内没有一个内核对象受信 61 break; 62 case WAIT_OBJECT_0 + 0: 63 // 句柄h[0]对应的内核对象受信 64 break; 65 case WAIT_OBJECT_0 + 1: 66 // 句柄h[1]对应的内核对象受信 67 break; 68 } 69 */