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
| #include <handleapi.h> #include <minwinbase.h> #include <minwindef.h> #include <processthreadsapi.h> #include <stdio.h> #include <synchapi.h> #include <windows.h> #include <winnt.h>
int g_dwTickets = 10; CRITICAL_SECTION cs;
DWORD WINAPI MyFirstThreadProc(LPVOID IpParameter) { while (1) { EnterCriticalSection(&cs); if (g_dwTickets <= 0) { LeaveCriticalSection(&cs); break; } printf("还有%d张票\n", g_dwTickets); g_dwTickets--; printf("卖出去一张,现在还有%d张\n", g_dwTickets); LeaveCriticalSection(&cs); } return 0; }
int main(int argc, char *argv[]) { DWORD dwR1,dwR2; HANDLE aThreadHandles[2];
InitializeCriticalSection(&cs); aThreadHandles[0] = CreateThread(NULL, 0, MyFirstThreadProc, NULL, 0, NULL); aThreadHandles[1] = CreateThread(NULL, 0, MyFirstThreadProc, NULL, 0, NULL); WaitForMultipleObjects(2, aThreadHandles, TRUE, INFINITE);
GetExitCodeThread(aThreadHandles[0], &dwR1); GetExitCodeThread(aThreadHandles[1], &dwR2); CloseHandle(aThreadHandles[0]); CloseHandle(aThreadHandles[1]); DeleteCriticalSection(&cs); return 0; }
|