Tag: SSE ble wait res his result put Inter int
For an unbounded blocking queue, its implementation is simple, with a lock (lock queue) + A conditional variable (empty). Then for a bounded blocking queue, its queue capacity is capped, in fact, just add a condition variable to determine whether full.
In conclusion, we need
- Mutex: Protect queue Read and write operations
- NOTEMPTYCV: Condition variable, wait at Take, after put notify
- NOTFULLCV: Condition variable, wait at put, notify after take.
C++11 provides a rich multi-threaded programming library, including locking unlocking, synchronization primitives and other packages. My implementation is as follows:
#pragma once//must use it higher than c++11#include <condition_variable> #include <mutex> #include <queue& GT, #include <vector> #include <assert.h> #include <iostream> #include <thread>using namespace Std::chrono_literals;template<typename T>class boundedblockingqueue {public://Make class non-copyable Bounde Dblockingqueue (const boundedblockingqueue<t>&) = delete; boundedblockingqueue& operator= (const boundedblockingqueue<t>&) = delete; Explicit boundedblockingqueue<t> (size_t maxSize): Mtx_ (), Maxsize_ (maxSize) {} void put (con St t& x) {//Std::cout << std::this_thread::get_id () << "puting" << x << Std::endl; Std::unique_lock<std::mutex> Locker (MTX_); Notfullcv_.wait (Locker, [this] () {return queue_.size () < maxsize_;}); ASSERT (Locker.owns_lock ()); ASSERT (Queue_.size () < maxsize_); Queue_.puSH (x); Notemptycv_.notify_one (); } T Take () {//Std::cout << std::this_thread::get_id () << "taking" << Std::endl; Std::unique_lock<std::mutex> Locker (MTX_); Notemptycv_.wait (Locker, [this] () {return!queue_.empty ();}); ASSERT (Locker.owns_lock ()); ASSERT (!queue_.empty ()); T Front (Queue_.front ()); Queue_.pop (); Notfullcv_.notify_one (); return front; }//With Time Out//@param Timeout:max wait time, MS//@param outres:reference result if take successfully @return take successfully or not bool take (int timeout, t& outres) {std::unique_lock<std::mutex> Locker (MTX_); Notemptycv_.wait_for (Locker, timeout*1ms, [this] () {return!queue_.empty ();}); ASSERT (Locker.owns_lock ()); if (Queue_.empty ()) return false; Outres = Queue_.front (); Queue_.pop (); Notfullcv_.notify_one (); return true; }//CheckingBlockingqueue status from outside//don't use with it as internal call, which would cause DEADLOCK bool empty () const { Std::unique_lock<std::mutex> Locker (MTX_); return Queue_.empty (); } size_t Size () const {std::unique_lock<std::mutex> locker (mtx_); return Queue_.size (); } size_t maxSize () const {return maxsize_; }private:mutable Std::mutex mtx_; Std::condition_variable notemptycv_; Std::condition_variable notfullcv_; size_t Maxsize_; Std::queue<t> Queue_;};
Implementing a bounded blocking queue with c++11