使用临界区机制同步线程

假如一个银行系统有两个线程执行取款任务,一个使用存折在柜台取款,一个使用银行卡在ATM取款。

下面是通过临界区来模拟这个例子。

临界区的使用只有四个函数:

初始化临界区,进入临界区,离开临界区,删除临界区。

声明一个临界区:CRITICAL_SECTION gCriticalSection;

初始化临界区:InitializeCriticalSection(&cs);

进入临界区:EnterCriticalSection(&cs);

离开临界区:LeaveCriticalSection(&cs);

删除临界区:DeleteCriticalSection(&cs);


//使用临界区机制同步线程
//两个写线程,通过临界区来更新一个变量值

#include <iostream>
#include <process.h>
#include <Windows.h>

using namespace std;

HANDLE evFin[2];
int total = 100;
CRITICAL_SECTION cs;

void WriteThread1(void* param){
	EnterCriticalSection(&cs);
	if (total - 90 >= 0){
		total -= 90;
		cout << "you witdraw 90." << endl;
	}
	else{
		cout << "you do not have that much money." << endl;
	}
	LeaveCriticalSection(&cs);
	SetEvent(evFin[0]);
}

void WriteThread2(void* param){
	EnterCriticalSection(&cs);
	if (total - 20 >= 0){
		total -= 20;
		cout << "you withdraw 20." << endl;
	}
	else{
		cout << "you do not have that much money" << endl;
	}
	LeaveCriticalSection(&cs);
	SetEvent(evFin[1]);
}

int main(){
	evFin[0] = CreateEvent(NULL, false, false, NULL);
	evFin[1] = CreateEvent(NULL, false, false, NULL);
	InitializeCriticalSection(&cs);
	_beginthread(WriteThread1, 0, NULL);
	_beginthread(WriteThread2, 0, NULL);

	WaitForMultipleObjects(2, evFin, true, INFINITE);
	DeleteCriticalSection(&cs);
	cout << total << endl;
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值