上一篇文章中使用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).