1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include <process.h> #include <Windows.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> struct ThreadNum{ char num; }; int const LOOP = 10; HANDLE g_hThreadEvent[3]; unsigned int __stdcall ThreadPrint(LPVOID); int main(_In_ int _Argc, char* Argv[]) { struct ThreadNum TNum[3]; TNum[0].num = 'A'; TNum[1].num = 'B'; TNum[2].num = 'C'; g_hThreadEvent[0] = CreateEvent(NULL, FALSE, TRUE, NULL); g_hThreadEvent[1] = CreateEvent(NULL, FALSE, FALSE, NULL); g_hThreadEvent[2] = CreateEvent(NULL, FALSE, FALSE, NULL); enum{MAXHANDLE = 3}; HANDLE handle[MAXHANDLE]; handle[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadPrint, (LPVOID)&TNum[0], 0, NULL); handle[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadPrint, (LPVOID)&TNum[1], 0, NULL); handle[2] = (HANDLE)_beginthreadex(NULL, 0, ThreadPrint, (LPVOID)&TNum[2], 0, NULL); WaitForMultipleObjects(MAXHANDLE, handle, TRUE, INFINITE); for (int i = 0; i < MAXHANDLE; ++i) { CloseHandle(handle[i]); } getchar(); return 0; } unsigned int __stdcall ThreadPrint(LPVOID p) { for (int i = 0 ; i < LOOP; ++i) { WaitForSingleObject(g_hThreadEvent[((ThreadNum*)p)->num - 'A'], INFINITE); printf("%c, 线程ID%5d\n", ((ThreadNum*)p)->num, GetCurrentThreadId()); SetEvent(g_hThreadEvent[(((ThreadNum*)p)->num - 'A' + 1)%3]); } _endthreadex(0); return 0; }
|