#include <windows.h> #include <stdio.h> DWORD WINAPI Fun1Proc(LPVOID lParam); DWORD WINAPI Fun2Proc(LPVOID lParam); int balance = 110;//账户余额[最少10元保底] CRITICAL_SECTION critical;//代码临界区 /* 运用关键代码端[临界区]实现线程间同步 */ void main() { InitializeCriticalSection(&critical); HANDLE hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);//线程1存钱[每次存100元,账户最多110元] HANDLE hThread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);//线程2取钱[每次取100元,账户至少留10元] CloseHandle(hThread1); CloseHandle(hThread2); Sleep(5000); DeleteCriticalSection(&critical); } DWORD WINAPI Fun1Proc(LPVOID lParam) { int i = 50; while (i-- > 0) { EnterCriticalSection(&critical); if (balance<110) { printf("线程1:/t账户余额:%d元,不足110元,线程1存入100元/n",balance); balance+=100; LeaveCriticalSection(&critical); continue; } printf("线程1:/t账户余额%d元,线程1等待线程2取款.../n",balance); LeaveCriticalSection(&critical); } return 0; } DWORD WINAPI Fun2Proc(LPVOID lParam) { int i=50; while (i-- > 0) { EnterCriticalSection(&critical); if (balance-100<10) { printf("线程2:/t账户余额:%d元,余额不足,线程2不能取款,等待线程1存款.../n",balance); LeaveCriticalSection(&critical); continue; } printf("线程2:/t账户余额%d元,线程2取款100元/n",balance); balance-=100; LeaveCriticalSection(&critical); } return 0; }