1. #include <windows.h>  
  2. #include <iostream.h>  
  3.  
  4. //线程入口函数声明  
  5. DWORD WINAPI Fun1Proc(  
  6.                         LPVOID lpParameter   // thread data  
  7.                         );  
  8.  
  9. DWORD WINAPI Fun2Proc(  
  10.                         LPVOID lpParameter   // thread data  
  11.                         );  
  12.  
  13. int tickets = 100;  //票数  
  14. CRITICAL_SECTION g_cs;   
  15.  
  16. void main()  
  17. {   
  18.     //线程句柄  
  19.     HANDLE hThread1;  
  20.     HANDLE hThread2;   
  21.  
  22.     //创建线程  
  23.     hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);  
  24.     hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);  
  25.  
  26.     //关闭线程句柄,因为主线程不需要再对线程操作  
  27.     CloseHandle(hThread1);  
  28.     CloseHandle(hThread2);  
  29.  
  30.     //初始化关键代码段  
  31.     InitializeCriticalSection(&g_cs);  
  32.  
  33.     //让主线程休眠4秒  
  34.     Sleep(4000);  
  35.  
  36.     //删除关键代码段  
  37.     DeleteCriticalSection(&g_cs);  
  38. }  
  39.  
  40.  
  41. //线程1的入口函数  
  42. DWORD WINAPI Fun1Proc(LPVOID lpParameter)  
  43. {  
  44.     while(TRUE)  
  45.     {  
  46.         EnterCriticalSection(&g_cs);  
  47.         if( tickets>0)  
  48.         {  
  49.             Sleep(1);  
  50.             cout<<"thread1 sell ticket: "<<tickets--<<endl;  
  51.             LeaveCriticalSection(&g_cs);  
  52.         }  
  53.         else 
  54.         {  
  55.             LeaveCriticalSection(&g_cs);  
  56.             break;  
  57.         }  
  58.     }  
  59.     return 0;  
  60. }  
  61.  
  62.  
  63.  
  64. //线程2的入口函数  
  65. DWORD WINAPI Fun2Proc(LPVOID lpParameter)  
  66. {  
  67.     while(TRUE)  
  68.     {  
  69.         EnterCriticalSection(&g_cs);      
  70.         if( tickets>0)  
  71.         {  
  72.             Sleep(1);  
  73.             cout<<"thread2 sell ticket: "<<tickets--<<endl;   
  74.             LeaveCriticalSection(&g_cs);          
  75.         }  
  76.         else 
  77.         {  
  78.             LeaveCriticalSection(&g_cs);  
  79.             break;  
  80.         }  
  81.     }  
  82.     return 0;  
  83. }  
  84.  
  85.  
  86.