#ifndef Net_frame_concurrent_queue_h#defineNet_frame_concurrent_queue_h#include<queue>#include<mutex>#include<condition_variable>Template<classType>/*Message Queuing Implementation*/ classConcurrentqueue {concurrentqueue&operator=(Constconcurrentqueue&) =Delete; Concurrentqueue (Constconcurrentqueue& Other) =Delete; Public: Concurrentqueue (): _queue (), _mutex (), _condition () {}Virtual~Concurrentqueue () {}voidPush (Type record) {Std::lock_guard<std::mutex>Lock(_mutex); _queue.push (record); _condition.notify_one (); } BOOLPop (type& record,BOOLisblocked =true) { if(isblocked) {Std::unique_lock<std::mutex>Lock(_mutex); while(_queue.empty ()) {_condition.wait (Lock); } } Else //If user wants to retrieve data in non-blocking mode{Std::lock_guard<std::mutex>Lock(_mutex); if(_queue.empty ()) {return false; }} record=Std::move (_queue.front ()); _queue.pop (); return true; } int32_t Size () {Std::lock_guard<std::mutex>Lock(_mutex); return_queue.size (); } BOOLEmpty () {Std::lock_guard<std::mutex>Lock(_mutex); return_queue.empty (); } Private: Std::queue<Type>_queue; mutable Std::mutex _mutex; Std::condition_variable _condition; }; #endif //Net_frame_concurrent_queue_h
(2) Implementation of a thread pool with Message Queuing
The. h file is as follows
#ifndef Net_frame_thread_pool_h#defineNet_frame_thread_pool_h#include"ConcurrentQueue.h"#include<vector>#include<queue>#include<memory>#include<thread>#include<mutex>#include<condition_variable>#include<future>#include<functional>#include<stdexcept>#defineMin_threads 10Template<classType>classThreadPool {ThreadPool&operator=(Constthreadpool&) =Delete; ThreadPool (Constthreadpool& Other) =Delete; Public: ThreadPool (int32_t threads, Std::function<void(type& record) >handler); Virtual~ThreadPool (); voidSubmit (Type record); Private: Private: BOOL_shutdown; int32_t _threads; Std::function<void(type& record) >_handler; Std::vector<std::thread>_workers; Concurrentqueue<Type>_tasks; }; Template<classType>ThreadPool<type>::threadpool (int32_t threads, std::function<void(Type &record) >handler): _shutdown (false), _threads (Threads), _handler (handler), _workers (), _task S () {if(_threads <min_threads) _threads=min_threads; for(Int32_t i =0; i < _threads; ++i) _workers.emplace_back ([ This] { while(!_shutdown) {Type record; _tasks. Pop (Record,true); _handler (record); } } ); } template<classType>ThreadPool<type>::~ThreadPool () { for(Std::thread &worker: _workers) Worker.join (); } template<classType>voidThreadpool<type>:: Submit (Type record) {_tasks. Push (record); } #endif //Net_frame_thread_pool_h
Implementation of C + + Message Queuing