1 #include "pch.h" 2 #include <iostream> 3 #include <windows.h> 4 5 using namespace std; 6 7 typedef struct MyData 8 { 9 const char* str; 10 }MYDATA; 11 12 //線程函數 13 DWORD WINAPI Fun(LPVOID lpParamter) 14 { 15 MYDATA *pmd = (MYDATA *)lpParamter; 16 for (int i = 0; i < 10; i++) 17 { 18 cout << "Displaying " << pmd->str << endl; 19 Sleep(500); 20 } 21 return 0; 22 23 } 24 25 int main() 26 { 27 //使用struct傳遞參數 28 MYDATA xstr; 29 xstr.str = "你好!"; 30 31 //使用GetExitCodeThread()輪詢檢查 32 //DWORD exitCode = 0; 33 //HANDLE hThread = CreateThread(NULL, 0, Fun, &xstr, 0, NULL); 34 //while (1) { 35 // GetExitCodeThread(hThread, &exitCode); // 嚴重浪費 CPU 時間 36 // if (STILL_ACTIVE != exitCode) 37 // break; 38 //} 39 //CloseHandle(hThread); 40 41 //WaitForSingleObject(),cpu使用率極低 42 HANDLE hThread = CreateThread(NULL, 0, Fun, &xstr, 0, NULL); 43 WaitForSingleObject(hThread, INFINITE); // 等待,直到線程被激發 44 CloseHandle(hThread); 45 46 cout << "Child thread is over." << endl; 47 return 0; 48 49 }
參考文章:
http://www.javashuo.com/article/p-nmgjlghf-gx.htmlhtml