先贴代码:
#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;
}
结果: