多线程编程-- 线程安全的queue II

上一篇文章中使用std::mutex 和 条件变量 std::condition_variable 实现了一个线程安全的队列。

这个队列是没有边界的, 也就是允许插入无限多的元素的,事实上这是不可能的, 当元素过多时候,插入元素会失效。这是很危险的一种行为。

下面来实现一个有边界的线程安全的队列 BoundedBlockingQueue

template <typename T>
class BoundedBlockingQueue {
  NOCOPY_CLASS(BoundedBlockingQueue);
 public:
  explicit BoundedBlockingQueue(size_t max_size): lock_(),
    cond_not_full_(&lock_), cond_not_empty_(&lock_), capacity_(max_size), queue_() {
    }

  ~BoundedBlockingQueue() { }

  // blocking pop
  T Pop() {
    LockGuard<MutexLock> guard(&lock_);
    while (queue_.empty()) {
      cond_not_empty_.Wait();
    }
    assert(!queue_.empty());
    T t = queue_.front();
    queue_.pop_front();
    cond_not_full_.Signal();
    return t;
  }

  // non-blocking pop
  bool TryPop(T& t) {
    LockGuard<MutexLock> guard(&lock_);
    if (!queue_.empty()) {
      t = queue_.front();
      cond_not_full_.Signal();
    }
    return false;
  }

  void Push(const T& t) {
    LockGuard<MutexLock> guard(&lock_);
    while (queue_.size() >= capacity_) {
      cond_not_full_.Wait();
    }
    assert(queue_.size() < capacity_);
    queue_.push_back(t);
    cond_not_empty_.Signal();
  }

  bool TryPush(const T& t) {
    LockGuard<MutexLock> guard(&lock_);
    if (queue_.size() < capacity_) {
      queue_.push_back(t);
      cond_not_empty_.Signal();
      return true;
    }
    return false;
  }

  size_t size() const {
    LockGuard<MutexLock> guard(&lock_);
    return queue_.size();
  }
  bool empty() const {
    LockGuard<MutexLock> guard(&lock_);
    return queue_.empty();
  }
  bool full() const {
    LockGuard<MutexLock> guard(&lock_);
    return queue_.size() == capacity_;
  }
  bool capacity() const {
    LockGuard<MutexLock> guard(&lock_);
    return capacity_;
  }

 private:
  mutable MutexLock lock_;
  ThreadCondition cond_not_full_;
  ThreadCondition cond_not_empty_;
  size_t capacity_;
  std::deque<T> queue_;
};

这里用到了两个条件变量,一个条件变量来判断queue 是否为空,
另一个条件变量来判断 queue 是否为满。利用两个条件变量便可以实现bounded 有边界的条件。

另外一点需要注意私有成员变量 lock_ , 这个变量被声明为mutable.
因为在empty(), full() 等函数中调用,而这些函数声明为const 成员函数。只有把将lock_ 声明为mutable 才能在const 成员函数中改变状态。

有了上面的 BoundedBlockingQueue, 实现一个线程池就比较容易了。
下一篇中来实现一个线程池(threadpool).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值