Reference: "C++11 in-depth application"
Resolve producer consumer problems with synchronous blocking queues.
Producer Consumer issues:
There is a producer in the production of products, these products will be provided to a number of consumers to spend, in order to enable producers and consumers to execute concurrently, in between a buffer pool with multiple buffers,
The producer puts the product it produces into a buffer, the consumer can take the product from the buffer to consume, all the producers and consumers are running asynchronously, but they must stay in sync,
That is, the consumer is not allowed to fetch products in an empty buffer, nor does it allow the producer to run the product into a buffer that is already full and has not been taken away.
//syncqueue.hpp#include <list>#include<mutex>#include<condition_variable>#include<iostream>Template<typename t>classsyncqueue{Private: BOOLIsfull ()Const { returnM_queue.size () = =m_maxsize; } BOOLIsEmpty ()Const { returnM_queue.empty (); } Public: Syncqueue (intmaxSize): M_maxsize (maxSize) {}voidPut (Constt&x) {Std::lock_guard<std::mutex>Locker (M_mutex); while(Isfull ()) {Std::cout<<"The blocking queue is full,waiting ..."<<Std::endl; M_notfull.wait (M_mutex); } m_queue.push_back (x); M_notempty.notify_one (); } voidTake (t&x) {Std::lock_guard<std::mutex>Locker (M_mutex); while(IsEmpty ()) {Std::cout<<"The blocking queue is empty,wating ..."<<Std::endl; M_notempty.wait (M_mutex); } x=M_queue.front (); M_queue.pop_front (); M_notfull.notify_one (); }Private: Std::list<T> M_queue;//buffersStd::mutex M_mutex;//mutex and conditional variables are used togetherStd::condition_variable_any M_notempty;//A condition variable that is not emptyStd::condition_variable_any M_notfull;//No full condition variable intM_maxsize;//maximum size of the synchronization queue};
Test:
//Test.cpp#include"syncqueue.hpp"#include<thread>#include<iostream>#include<chrono>Syncqueue<int> Syncqueue (5);voidProduce () { for(inti =0; I < the; ++i) {std::this_thread::sleep_for (Std::chrono::seconds (1)); Syncqueue.put (888); Std::cout<<"put (888)"<<Std::endl; }}voidconsume () {intx =0; for(inti =0; I <5; ++i) {std::this_thread::sleep_for (Std::chrono::seconds (1)); Syncqueue.take (x); Std::cout<<"Take (888)"<<Std::endl; }}intMainvoid) {Std::thread producer (produce); Std::thread Consumer1 (consume); Std::thread Consumer2 (consume); Std::thread Consumer3 (consume); Producer.join (); Consumer1.join (); Consumer2.join (); Consumer3.join (); return 0;}
C + + synchronization blocking queue