C++ std::thread 简单的生产者和消费者
2017-04-12 21:38
239 查看
#include <iostream> #include <thread> #include <mutex> #include <deque> #include <vector> #include <unistd.h> std::deque<int> data; std::mutex m_mux;//全局互斥锁 int num=0; void product_thread(){ while(true){ std::unique_lock<std::mutex> lck(m_mux); num = ++num % 1000; data.push_front(num); printf("product %d\n", num); lck.unlock(); sleep(2); } } void consume_thread(){ while (true){ std::unique_lock<std::mutex> lck(m_mux); if(data.empty()) { lck.unlock(); continue; } printf("consume %d\n", data.back()); data.pop_back(); lck.unlock(); sleep(5); } } int main() { std::thread thread_product(&product_thread); std::cout<<"Now it runs after the thread_product function !"<<std::endl; std::thread thread (&consume_thread); std::cout<<"Now it runs after 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; return 0; }
相关文章推荐
- (转)一段生产者和消费者的简单多线程代码
- Java多线程,生产者,消费者回顾.简单的一条街包子铺!
- 一种简单高效的生产者消费者多线程实现
- 关于消费者.生产者,缓冲区的简单java实现
- Poco::Thread 生产者消费者Demo
- 简单实现生产者、消费者模型
- 生产者和消费者并发模式的几种简单写法
- Java- 简单了解线程 生产者与消费者问题(三)
- Ruby简单的生产者,消费者模式的实现
- 多线程--生产者消费者--简单例子
- 一个简单的C语言操作系统生产者消费者模型
- 使用semaphore实现生产者-消费者简单模型
- 简单消费者生产者问题
- boost c++ lib on linux(4) - thread同步条件变量学习——生产者消费者队列
- 简单实现带有数据缓冲池的生产者消费者模型
- java多线程之生产者与消费者问题的简单模拟
- Thread--不同步的生产者与消费者
- java简单小结(附一个java实现的生产者消费者问题的程序)
- 一个简单的生产者/消费者例子
- 在python中实现生产者和消费者的例子(四):使用thread模块和全局变量