模拟订票系统学习多线程
2012-03-11 17:44
232 查看
#include <windows.h> #include <IOSTREAM.H> //线程函数声明 DWORD WINAPI FuncProc1( LPVOID lpParameter//thread data ); DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data ); //int index = 0; int tickets = 100; HANDLE hMutex; //互斥对象 int main() { HANDLE hThread1; HANDLE hThread2; hThread1 = CreateThread(NULL,//pointer to security attributes 0, //initial thread stack size FuncProc1, // pointer to thread function NULL, // argument for new thread 0, // creation flags NULL); // pointer to receive thread ID hThread2 = CreateThread(NULL, 0, FuncProc2, NULL, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); /*while (index++ < 1000) { cout << "main thread is running" << endl; }*/ hMutex = CreateMutex(NULL,// pointer to security attributes TRUE, // flag for initial ownership "tickets" // pointer to mutex-object name ); //可以利用上用"tickets"命名来判断只能运行一个实例 if (hMutex) { if (ERROR_ALREADY_EXISTS == GetLastError()) { cout << "Only one instance can run!" << endl; return 0; } } /* 这个地方线程互斥量已在主线程中,执行下面该语句名互斥量变为2, 则下面ReleaseMutex函数需要执行两次才能完全释放,让子线程去执行*/ WaitForSingleObject(hMutex,INFINITE); ReleaseMutex(hMutex);//此处需要释放主线程创建时得到的互斥量,否则子线程不执行 ReleaseMutex(hMutex);// Sleep(4000); return 0 ; } //线程函数定义 DWORD WINAPI FuncProc1(LPVOID lpParameter //thread data ) { /*while(index++ < 1000) { cout << "thread1 is running" << endl; }*/ while(TRUE) { //ReleaseMutex(hMutex); WaitForSingleObject(hMutex,//handle to object to wait for INFINITE //time-out interval in milliseconds:INFINITE, the function's time-out interval never elapses. ); if (tickets>0) { Sleep(10); cout << "Thread1 sell tickets: " << tickets-- << endl; } else { break; } ReleaseMutex(hMutex); } return 0; }; DWORD WINAPI FuncProc2( LPVOID lpParameter//thread data ) { while(TRUE) { //ReleaseMutex(hMutex); WaitForSingleObject(hMutex,INFINITE); if (tickets>0) { Sleep(10); cout << "Thread2 sell tickets: " << tickets-- << endl; } else { break; } ReleaseMutex(hMutex); } return 0; }
相关文章推荐
- 模拟订票系统学习多线程
- 用java多线程操作模拟售票系统
- iOS学习笔记——多线程(简单售票系统)
- 数字水印学习系统之六 攻击模拟
- <模拟飞机票订票和退票系统>的c++实现
- 利用readwritelock简单模拟实现多线程下cache的系统
- 多线程学习使用(二)——仿真之饭店服务系统
- C语言模拟学生管理系统链表学习
- linux系统相关学习:多线程
- Java学习之:多线程(模拟售票)
- 模拟售票,学习多线程
- java 多线程模拟售票系统
- 用多线程模拟生产零件系统程序
- 卖票——多线程模拟卖票系统
- java多线程学习之死锁的模拟和避免
- c++并发编程,简单模拟飞机订票系统
- 模拟火车票购票系统的简单多线程程序
- java多线程模拟有会话的访问web系统,并记录访问日志
- C#模拟超人和小怪兽赛跑——多线程学习之(二)牛刀小试
- JAVA 并发-多线程读写锁之模拟缓存系统(11)