简单实例
使用同步数据锁
#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>
#include<bits/stdc++.h>
#include<conio.h>
using namespace std;
mutex mu; //线程互斥对象
int Maxsize = 10;
int Buffer=0;
int k=1;
void Producer()
{
while (k)
{
if(Buffer < Maxsize)
{
mu.lock(); //同步数据锁
Buffer++;
cout <<"生产者生产一个产品,当前拥有:"<< Buffer << endl;
mu.unlock(); //解除锁定
Sleep(400);
}
else
{cout <<"仓库已满,暂不生产,当前拥有:"<< Buffer << endl;
Sleep(2000);
}
}
return;
}
void Consumer()
{
while (k)
{mu.lock();
if(Buffer > 0)
{
Buffer--;
cout <<"消费者1消费一个产品,剩余产品:"<< Buffer << endl;
mu.unlock();
Sleep(2000);
}
else
{
cout <<"产品不足,等待生产,剩余产品:"<< Buffer << endl;
mu.unlock();
Sleep(2000);
}
//mu.unlock();
}
return;
}
void Consumer1()
{
while (k)
{mu.lock();
if(Buffer > 0)
{
Buffer--;
cout <<"消费者2消费一个产品,剩余产品:"<< Buffer << endl;
mu.unlock();
Sleep(2000);
}
else
{
cout <<"产品不足,等待生产,剩余产品:"<< Buffer << endl;
mu.unlock();
Sleep(2000);
}
//mu.unlock();
}
return;
}
int main()
{
thread task01(Producer);
thread task02(Consumer);
thread task03(Consumer1);
task01.detach();
task02.detach();
task03.detach();
char ch;
ch=getch();
if(ch=='p')
{
k=0;
return 0;
}
//system("pause");
}