C++11多线程库用法初试牛刀

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值