假如一个银行系统有两个线程执行取款任务,一个使用存折在柜台取款,一个使用银行卡在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;
}