- #include <windows.h>
- #include <iostream.h>
- //线程入口函数声明
- DWORD WINAPI Fun1Proc(
- LPVOID lpParameter // thread data
- );
- DWORD WINAPI Fun2Proc(
- LPVOID lpParameter // thread data
- );
- int tickets = 100; //票数
- CRITICAL_SECTION g_cs;
- void main()
- {
- //线程句柄
- HANDLE hThread1;
- HANDLE hThread2;
- //创建线程
- hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
- hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
- //关闭线程句柄,因为主线程不需要再对线程操作
- CloseHandle(hThread1);
- CloseHandle(hThread2);
- //初始化关键代码段
- InitializeCriticalSection(&g_cs);
- //让主线程休眠4秒
- Sleep(4000);
- //删除关键代码段
- DeleteCriticalSection(&g_cs);
- }
- //线程1的入口函数
- DWORD WINAPI Fun1Proc(LPVOID lpParameter)
- {
- while(TRUE)
- {
- EnterCriticalSection(&g_cs);
- if( tickets>0)
- {
- Sleep(1);
- cout<<"thread1 sell ticket: "<<tickets--<<endl;
- LeaveCriticalSection(&g_cs);
- }
- else
- {
- LeaveCriticalSection(&g_cs);
- break;
- }
- }
- return 0;
- }
- //线程2的入口函数
- DWORD WINAPI Fun2Proc(LPVOID lpParameter)
- {
- while(TRUE)
- {
- EnterCriticalSection(&g_cs);
- if( tickets>0)
- {
- Sleep(1);
- cout<<"thread2 sell ticket: "<<tickets--<<endl;
- LeaveCriticalSection(&g_cs);
- }
- else
- {
- LeaveCriticalSection(&g_cs);
- break;
- }
- }
- return 0;
- }