用C++写一个同步互斥售票系统

// 20200713.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <iostream>
#include<Windows.h>
using namespace std;
static int ticket=0;

//winapi 表明是C语言函数只能用C语言来编译
//线程回调函数threadFun.

DWORD WINAPI threadFun1(LPVOID lpvoid)
{
	HANDLE handle = *(HANDLE *)lpvoid; //获取句柄
	while(1)
	{
		WaitForSingleObject(handle,INFINITE);  //等待信号量
		if(ticket>=100)
		{
			cout<<"卖完了"<<endl;
			break;
		}
		ticket++;
		cout<< " window 1:卖出了"<<ticket<<"张票"<<endl;
		ReleaseMutex(handle); //释放信号量
	}
	return 0;
}

DWORD WINAPI threadFun2(LPVOID lpvoid)
{
	HANDLE handle = *(HANDLE *)lpvoid;
	while(1)
	{
		WaitForSingleObject(handle,INFINITE);
		if(ticket>=100)
		{
			cout<<"卖完了"<<endl;
			break;
		}
		ticket++;
		cout<<"window 2:卖出了"<<ticket<<"张票"<<endl;
		ReleaseMutex(handle);
	}
	return 0;
}

DWORD WINAPI threadFun3(LPVOID lpvoid)
{
	HANDLE handle = *(HANDLE *)lpvoid;
	while(1)
	{
		WaitForSingleObject(handle,INFINITE);
		if(ticket>=100)
		{
			cout<<"卖完了"<<endl;
			break;
		}
		ticket++;
		cout<<"window 3:卖出了"<<ticket<<"张票"<<endl;
		ReleaseMutex(handle);
	}
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE mutexHandle =CreateMutex(NULL,FALSE,_T(""));  //创建信号量,类似于配“锁”
	HANDLE handleThread1; //创建句柄
	DWORD dwThread1; //unsigned long ,它是MFC的数据类型。
	handleThread1 = CreateThread(NULL,0,threadFun1,&mutexHandle,0,&dwThread1);
	if(handleThread1 == NULL)
	{
		 return -1;
	}

	HANDLE handleThread2;  
	DWORD dwThread2;
	handleThread2 = CreateThread(NULL,0,threadFun2,&mutexHandle,0,&dwThread2);
	if(handleThread2 == NULL)
	{
		 return -1;
	}

	HANDLE handleThread3;
	DWORD dwThread3;
	handleThread3 = CreateThread(NULL,0,threadFun3,&mutexHandle,0,&dwThread3);
	if(handleThread3 == NULL)
	{
		 return -1;
	}
	//异常判断

	Sleep(1000); //睡眠函数,避免发生主函数先运行完毕,然后子线程不启动了。
	return 0;
}


用C++写一个同步互斥售票系统_第1张图片

你可能感兴趣的:(学习,C++)