赞
踩
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
std::deque<int> data;
std::mutex m_mux;//全局互斥锁
int num = 0;
int count = 0;
int counta = 1000;
void product_thread() {
while (true) {
std::unique_lock<std::mutex> lck(m_mux);
num = ++num % 1000;
if (num == 20)
{
std::cout << "生产完毕" << std::endl;
printf("生产num =%d\n", num);
break;
}
if (data.size() >= 10)
{
lck.unlock();
printf("生产已经过剩 等待消费 队列一共有数据%d的\n", data.size());
_sleep(200);
continue;
}
printf("生产队列一共有数据%d 没有饱和继续生产\n", data.size());
printf("生产num =%d\n", num);
data.push_front(num);
printf("生产 %d号产品\n", num);
count = data.size();
lck.unlock();
_sleep(rand()%10);
}
}
void consume_thread() {
while (true) {
std::unique_lock<std::mutex> lck(m_mux);
if (data.empty()) {
lck.unlock();
printf("消费太快 等待生产 一共有缓存队列%d的\n", data.size());
_sleep(200);
continue;
}
printf("消耗 %d\n", data.back());
if (num == 20)
{
std::cout << "停止消费 消费退出" << std::endl;
printf("消费 num =%d \n", num);
break;
}
printf("消费 num =%d \n", num);
data.pop_back();
lck.unlock();
_sleep(10);
}
}
int main() {
std::thread thread_product(&product_thread);
std::cout << "Now it runs before the thread_product function !" << std::endl;
std::thread thread(&consume_thread);
std::cout << "Now it runs before the thread function !" << std::endl;
thread_product.join();
std::cout << "Now it runs after the thread_product function !" << std::endl;
thread.join();
std::cout << "Now it runs after the thread.join function !" << std::endl;
thread.detach();
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。