目录
1.铺垫
先提一个小场景,有1000张票,现在有4个进程,这四个进程疯狂的去抢这1000张票,看看会发生什么呢?
#include <iostream>
#include <thread>
#include <unistd.h>
#include <vector>
#include "thread.hpp"
class ticket
{
public:
static int tickets;//总共的票数
ticket(std::string &name)
:_name(name)
{}
std::string &name()
{
return _name;
}
int _count = 0;//抢到多少票
std::string _name;//线程的名字
};
int ticket::tickets = 1000;
void handler(ticket *t)
{
while(true)
{
if(t->tickets > 0)
{
usleep(10000);
std::cout<< t->name()<<"tickets-garbbing ticket:"<<t->tickets<<std::endl;
t->tickets--;
t->_count++;
}
else
{
break;
}
}
}
using namespace mythread;//自己封装的线程库
int count = 4;
int main()
{
std::vector<thread<ticket*>> threads;
// 创建一批线程
std::vector<ticket*> data;
for (int i = 0; i < count; i++)
{
std::string name = "thread" + std::to_string(i);
ticket *t = new ticket(name);
data.push_back(t);
threads.emplace_back(handler, t, name);
}
//启动一批线程
for(auto &t : threads)
{
t.start();
}
//等待一批线程
for(auto &t : threads)
{
std::cout <<t.name() <<" wait sucess "<<std::endl;
t.join();
}
//查看结果
for(auto p : data)
{
std::cout << p->_name<<" get tickets "<<p->_count<<std::endl;
sleep(1);
}
return 0;
}
我们发现这四个线程竟然把票数抢到负数了,代码中已经判断if(t->tickets > 0)为什么票数还会减为0呢?
假设当前tickets只剩下1时。
thread0进行判断,thread0发现票数是大于0的,他就会进入循环,但是这个时候thread0的时间片到了,thread0进入等待队列。
thread1开始执行,thread1进行判断,thread1发现票数也是大于0的,进入循环,这个时候hread1的时间片到了,thr