#include<thread>
#include<iostream>
#include<vector>
#include<mutex>
#include<random>
#include<Windows.h>
using namespace std;
//定义一个全局的数据池,多个线程从该数据池中获取数据,多个线程向该数据池中添加数据
vector<int> gDataPool;
int gCnt = 0;
mutex g_lock;
void producerThread()
{
while (true)
{
if (g_lock.try_lock())
{
random_device r;
int data = r();
std::cout << "\nproducer "<<this_thread::get_id()<<" get the lock and create an data, value=" << data << endl;
gDataPool.push_back(data);
g_lock.unlock();
}
else
{
std::cout << "\nproducer "<< this_thread::get_id() <<" get the lock fail" << endl;
}
std::this_thread::sleep_for(chrono::seconds(1));
gCnt++;
if (gCnt > 20)
break;
}
}
void customerThread()
{
while (true)
{
if (g_lock.try_lock())
{
if (gDataPool.size() > 0)
{
int data = gDataPool.back();
gDataPool.pop_back();
std::cout << "\ncustomer " << this_thread::get_id() << " get the lock, and get the data, value=" << data << endl;
}
g_lock.unlock();
}
else
{
std::cout << "\ncustomer " << this_thread::get_id() <<" can not get the lock" << endl;
}
std::this_thread::sleep_for(chrono::seconds(1));
gCnt++;
if (gCnt > 50)
break;
}
}
int main()
{
thread t1(producerThread);
thread t2(customerThread);
t1.join(); //阻塞main线程,直到t1线程执行完
t2.join(); //阻塞main线程,直到t2线程执行完
std::cout << "all thread find its execution" << std::endl;
return 0;
}
#include<iostream>
#include<vector>
#include<mutex>
#include<random>
#include<Windows.h>
using namespace std;
//定义一个全局的数据池,多个线程从该数据池中获取数据,多个线程向该数据池中添加数据
vector<int> gDataPool;
int gCnt = 0;
mutex g_lock;
void producerThread()
{
while (true)
{
if (g_lock.try_lock())
{
random_device r;
int data = r();
std::cout << "\nproducer "<<this_thread::get_id()<<" get the lock and create an data, value=" << data << endl;
gDataPool.push_back(data);
g_lock.unlock();
}
else
{
std::cout << "\nproducer "<< this_thread::get_id() <<" get the lock fail" << endl;
}
std::this_thread::sleep_for(chrono::seconds(1));
gCnt++;
if (gCnt > 20)
break;
}
}
void customerThread()
{
while (true)
{
if (g_lock.try_lock())
{
if (gDataPool.size() > 0)
{
int data = gDataPool.back();
gDataPool.pop_back();
std::cout << "\ncustomer " << this_thread::get_id() << " get the lock, and get the data, value=" << data << endl;
}
g_lock.unlock();
}
else
{
std::cout << "\ncustomer " << this_thread::get_id() <<" can not get the lock" << endl;
}
std::this_thread::sleep_for(chrono::seconds(1));
gCnt++;
if (gCnt > 50)
break;
}
}
int main()
{
thread t1(producerThread);
thread t2(customerThread);
t1.join(); //阻塞main线程,直到t1线程执行完
t2.join(); //阻塞main线程,直到t2线程执行完
std::cout << "all thread find its execution" << std::endl;
return 0;
}