c++编写的多线程售票的例子
2011-03-25 13:18
501 查看
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1Proc(LPVOID lpParameter);//线程入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter);//线程入口函数
int tickets=100;//总共的票数
HANDLE hMutex;//互斥锁句柄
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);
//创建匿名的互斥锁对象
hMutex=CreateMutex(NULL,FALSE,NULL);
//cout<<"main thread is running"<<endl;
Sleep(4000);
}
//线程1的入口函数
DWORD WINAPI Fun1Proc(LPVOID lpParameter){
//cout<<"thead1 is running"<<endl;
while(true){
WaitForSingleObject(hMutex,INFINITE);//获得锁
if(tickets>0){
Sleep(1);
cout<<"thread1 sell ticket:"<<tickets--<<endl;
}else{
break;
}
ReleaseMutex(hMutex);//释放锁
}
return 0;
}
//线程2的入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter){
//cout<<"thead2 is running"<<endl;
while(true){
WaitForSingleObject(hMutex,INFINITE);// 获得锁
if(tickets>0){
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}else{
break;
}
ReleaseMutex(hMutex);//释放锁
}
return 0;
}
#include <iostream.h>
DWORD WINAPI Fun1Proc(LPVOID lpParameter);//线程入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter);//线程入口函数
int tickets=100;//总共的票数
HANDLE hMutex;//互斥锁句柄
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);
//创建匿名的互斥锁对象
hMutex=CreateMutex(NULL,FALSE,NULL);
//cout<<"main thread is running"<<endl;
Sleep(4000);
}
//线程1的入口函数
DWORD WINAPI Fun1Proc(LPVOID lpParameter){
//cout<<"thead1 is running"<<endl;
while(true){
WaitForSingleObject(hMutex,INFINITE);//获得锁
if(tickets>0){
Sleep(1);
cout<<"thread1 sell ticket:"<<tickets--<<endl;
}else{
break;
}
ReleaseMutex(hMutex);//释放锁
}
return 0;
}
//线程2的入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter){
//cout<<"thead2 is running"<<endl;
while(true){
WaitForSingleObject(hMutex,INFINITE);// 获得锁
if(tickets>0){
Sleep(1);
cout<<"thread2 sell ticket:"<<tickets--<<endl;
}else{
break;
}
ReleaseMutex(hMutex);//释放锁
}
return 0;
}
相关文章推荐
- c++编写断点续传和多线程下载模块【转】
- Linux C 多线程编写-----例子:10个售票窗口协作卖掉150张票
- C++中多线程编写时,缺少pthread.h文件的处理办法
- c++编写node的addon(10) --例子 蒙特卡罗法估算PI
- 使用C++编写的一个Find(查找)对话框例子
- Java使用Eclipse_cdt和MinGw编写C++/java,jni的小例子
- C++多线程 例子
- mfc c++ 多线程AfxBeginThread 例子( 一)
- 多线程售票例子
- Linux下,使用C/C++编写"静态链接库"的一个简单例子
- linux 下用eclipse 编写多线程C++项目
- 两种方式实现多线程共享资源(典型的售票例子)
- windows下c++编写多线程
- c++编写断点续传和多线程下载模块【转】
- windows qt 使用c++ posix接口编写多线程程序(真神奇)good
- 编写 三个类 ticket,sealWindow,ticketSealCenter,代表票信息,售票窗口,售票中心, 售票中心分配一定数量的票(多个窗口实现多线程售票)
- C++ 多线程 火车站售票
- c++多线程编写网络聊天室程序(socket)
- java多线程售票小例子
- 通过例子学设计模式之--单例模式以及多线程下说明(C++实现)