多线程售票程序(C++11 线程互斥锁的使用)

本文探讨了在多线程环境下实现票务系统的正确性问题。通过使用互斥锁将票数查询与减一操作封装为原子操作,解决了并发场景下票数不一致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先贴代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <windows.h>
using namespace std;	
static int ticks = 100;
class SaleTick {
public:
	void Main()
	{
		for (;;)
		{
			
			if (ticks <= 0)
				break;
			ticks--;
			sale++;
			Sleep(1);
		}
		cout << "In SaleTick[" << ID <<']'<<sale<< endl;
	}
	int sale = 0;
	int ID;
};

int main()
{
	SaleTick st1;
	st1.ID = 9;
	SaleTick st2;
	st2.ID = 8;
	thread th1(&SaleTick::Main, &st1);	
	thread th2(&SaleTick::Main, &st2);	
	//th1.detach();
	//th2.detach();
	th1.join();
	th2.join();

	getchar();
	return 0;
}

然后问题就出现了:共卖出了103张票,总共才有100张!

这需要把票的查询和票的减少变成一个原子操作。原子操作:要么都执行,要么都不执行。

尽晚锁,尽早放。

#include <iostream>
#include <thread>
#include <mutex>
#include <windows.h>
using namespace std;
static int ticks = 100;
static mutex mu;
class SaleTick {
public:
	void Main()
	{
		for (;;)
		{
			mu.lock();
			if (ticks <= 0)
			{
				mu.unlock();
				break;
			}
			ticks--;
			mu.unlock();
			sale++;
			Sleep(1);
		}
		
	}
	int sale = 0;
	int ID;
};

int main()
{
	SaleTick st1;
	st1.ID = 9;
	SaleTick st2;
	st2.ID = 8;
	thread th1(&SaleTick::Main, &st1);
	thread th2(&SaleTick::Main, &st2);
	//th1.detach();
	//th2.detach();
	th1.join();
	th2.join();
	cout << "s1 sale [" << st1.sale << ']' << endl;
	cout << "s2 sale [" << st2.sale << ']' << endl;

	getchar();
	return 0;
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值