muduo之BlockingQueue
生活随笔
收集整理的這篇文章主要介紹了
muduo之BlockingQueue
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ?BlockingQueue是muduo是無界隊列,利用隊列(deque)實現,向隊列中加入和取出元素用互斥量和條件變量結合的方式來操作,就是一個線程同步的問題。
BlockingQueue.h
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_BLOCKINGQUEUE_H #define MUDUO_BASE_BLOCKINGQUEUE_H#include "muduo/base/Condition.h" #include "muduo/base/Mutex.h"#include <deque> #include <assert.h>namespace muduo { //互斥鎖配合條件變量是為了防止線程不停的主動獲得鎖、檢查條件、釋放鎖、再獲得鎖、再檢查、再釋放,一直到滿足運行的條件的時候才行 template<typename T> class BlockingQueue : noncopyable //無界阻塞隊列 {public:BlockingQueue(): mutex_(),notEmpty_(mutex_), //條件變量queue_(){}void put(const T& x){MutexLockGuard lock(mutex_);queue_.push_back(x);notEmpty_.notify(); // wait morphing saves us// http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/}void put(T&& x){MutexLockGuard lock(mutex_);queue_.push_back(std::move(x));notEmpty_.notify();//向所有線程提示條件已發生}T take(){MutexLockGuard lock(mutex_);// always use a while-loop, due to spurious wakeupwhile (queue_.empty()){notEmpty_.wait(); //等待條件發生}assert(!queue_.empty());T front(std::move(queue_.front()));//掏空queue_.front(),queue_.front()就變為空了queue_.pop_front();return std::move(front);}size_t size() const{MutexLockGuard lock(mutex_);return queue_.size();}private:mutable MutexLock mutex_;Condition notEmpty_ GUARDED_BY(mutex_);std::deque<T> queue_ GUARDED_BY(mutex_); };} // namespace muduo#endif // MUDUO_BASE_BLOCKINGQUEUE_H?
總結
以上是生活随笔為你收集整理的muduo之BlockingQueue的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: muduo之AsyncLogging
- 下一篇: muduo之FileUtil