1 #include<windows.h> 2 #include<stdio.h> 3 #include<string.h> 4 //#include <afxmt.h> 5 #define T_MAX 100 6 int ticket; 7 CRITICAL_SECTION CriticalSection; 8 /* //售票线程 9 DWORD WINAPI SaleThread(LPVOID lp) 10 { 11 int n = (int) lp; 12 while (ticket > 0) 13 { 14 printf("SaleThread%d sell %dth ticket\n", n, T_MAX-ticket+1); 15 ticket--; 16 Sleep(500); 17 } 18 return 0; 19 } 20 21 void MyThread() 22 { 23 HANDLE handle1,handle2,handle3,handle4,handle5; 24 //5个售票线程 25 handle1 = CreateThread(NULL,NULL,SaleThread,(void*)1,NULL,NULL); 26 handle2 = CreateThread(NULL,NULL,SaleThread,(void*)2,NULL,NULL); 27 handle3 = CreateThread(NULL,NULL,SaleThread,(void*)3,NULL,NULL); 28 handle4 = CreateThread(NULL,NULL,SaleThread,(void*)4,NULL,NULL); 29 handle5 = CreateThread(NULL,NULL,SaleThread,(void*)5,NULL,NULL); 30 } 31 */ 32 33 //售票线程 34 DWORD WINAPI SaleThread(LPVOID lp) 35 { 36 int n = (int) lp; 37 while (ticket > 0) 38 { //临界区同步 39 EnterCriticalSection(&CriticalSection); 40 printf("SaleThread%d sell %dth ticket\n", n, T_MAX-ticket+1); 41 ticket--; 42 LeaveCriticalSection(&CriticalSection); 43 Sleep(500); 44 } 45 return 0; 46 } 47 void MyThread() 48 { 49 HANDLE handle1,handle2,handle3,handle4,handle5; 50 //5个售票线程 51 handle1 = CreateThread(NULL,NULL,SaleThread,(void*)1,NULL,NULL); 52 handle2 = CreateThread(NULL,NULL,SaleThread,(void*)2,NULL,NULL); 53 handle3 = CreateThread(NULL,NULL,SaleThread,(void*)3,NULL,NULL); 54 handle4 = CreateThread(NULL,NULL,SaleThread,(void*)4,NULL,NULL); 55 handle5 = CreateThread(NULL,NULL,SaleThread,(void*)5,NULL,NULL); 56 } 57 58 int main(int argc, char* argv[]) 59 { 60 ticket=100; 61 //创建临界区对象 62 InitializeCriticalSection(&CriticalSection); 63 if(ticket>0) 64 MyThread(); 65 Sleep(50000); 66 //删除临界区对象 67 DeleteCriticalSection(&CriticalSection); 68 return 0; 69 }
时间: 2024-11-05 20:30:56