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
| 真有序 #include <handleapi.h> #include <minwindef.h> #include <processthreadsapi.h> #include <stdio.h> #include <synchapi.h> #include <windef.h> #include <windows.h> #include <winnt.h>
int g_Max = 10; int g_Number = 0; HANDLE hE; HANDLE hD; DWORD WINAPI ThreadProduct(LPVOID lsParameter){ for (int i = 0; i < g_Max; i++) { WaitForSingleObject(hE, INFINITE); g_Number = 1; DWORD id = GetCurrentThreadId(); printf("生产者%lx将数据%d放入缓存区\n",id,g_Number); SetEvent(hD); } return 0; }
DWORD WINAPI ThreadConsumer(LPVOID lsParameter){ for (int i = 0; i < g_Max; i++) { WaitForSingleObject(hD, INFINITE); g_Number = 0; DWORD id = GetCurrentThreadId(); printf("消费者%lx将数据%d放入缓存区\n",id,g_Number); SetEvent(hE);
} return 0; }
int main(int argc, char *argv[]) { HANDLE aThread[2]; hE = CreateEventA(NULL, FALSE, TRUE, NULL); hD = CreateEventA(NULL, FALSE, FALSE, NULL); aThread[0] = CreateThread(NULL, 0, ThreadProduct, NULL, 0, NULL); aThread[1] = CreateThread(NULL, 0, ThreadConsumer, NULL, 0, NULL);
WaitForMultipleObjects(2, aThread, TRUE, INFINITE); CloseHandle(aThread[0]); CloseHandle(aThread[1]); CloseHandle(hD); CloseHandle(hE); return 0; }
|