如下爲三個線程分別打印A、B和C,代碼中採用Event來同步線程,保證按照ABC的順序循環打印。ios
同志們如有更好的作法,請指教,謝謝!windows
附:這裏有問題,對於線程關閉最好的作法是天然結束,可是工做中經常遇到的是須要線程函數中來個while,哪位兄弟能兼容解決這個問題? 請不吝賜教!~函數
#include <conio.h> #include <windows.h> #include <iostream> using namespace std; DWORD WINAPI DealThreadA(void* para) { HANDLE handle = *(HANDLE*)para; while (1) { WaitForSingleObject(handle, INFINITE); cout<<"A.."<<endl; ResetEvent(handle); } return 0; } DWORD WINAPI DealThreadB(void* para) { HANDLE handle = *(HANDLE*)para; while (1) { WaitForSingleObject(handle, INFINITE); cout<<"B.."<<endl; ResetEvent(handle); } return 0; } DWORD WINAPI DealThreadC(void* para) { HANDLE handle = *(HANDLE*)para; while (1) { WaitForSingleObject(handle, INFINITE); cout<<"C.."<<endl<<endl; ResetEvent(handle); } return 0; } bool IsEventHasSignal(HANDLE handle) { if(WAIT_OBJECT_0 == WaitForSingleObject(handle, 0)) return true; return false; } void WaitEventSignalBeResponsed(HANDLE handle) { while (IsEventHasSignal(handle)) Sleep(1); } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hA = CreateEvent(NULL, TRUE, FALSE, NULL); HANDLE hB = CreateEvent(NULL, TRUE, FALSE, NULL); HANDLE hC = CreateEvent(NULL, TRUE, FALSE, NULL); CreateThread(0, 0, DealThreadA, (void*)&hA, 0, 0); CreateThread(0, 0, DealThreadB, (void*)&hB, 0, 0); CreateThread(0, 0, DealThreadC, (void*)&hC, 0, 0); while (!_kbhit()) { Sleep(1000); SetEvent(hA); WaitEventSignalBeResponsed(hA); SetEvent(hB); WaitEventSignalBeResponsed(hB); SetEvent(hC); WaitEventSignalBeResponsed(hC); } CloseHandle(hA); CloseHandle(hB); CloseHandle(hC); return 0; }