【发布时间】:2014-09-17 12:47:00
【问题描述】:
我实现了一个线程安全的模板化队列:
template<class T> class queue {
private:
boost::mutex mutex;
boost::condition_variable emptyCondition;
boost::condition_variable fullCondition;
boost::scoped_ptr< std::queue<T> > std_queue;
...
public:
...
T pop() {
T r; // [*]
{
boost::mutex::scoped_lock popLock(mutex);
while (queueIsEmpty())
emptyCondition.wait(popLock);
r = std_queue->front();
std_queue->pop();
}
fullCondition.notify_one();
return r;
}
...
由于缺少 T 的构造函数,没有形式参数,我无法以我的方式实例化对象(标记为 [*])。
那么:有没有办法,可能使用指向T 的指针和复制构造函数(我知道它是为每个T 实现的)来避免许多模板特化?
编辑 1
我也想过这个可能的解决方案。
T pop() {
boost::mutex::scoped_lock popLock(mutex);
while (queueIsEmpty())
emptyCondition.wait(popLock);
T r(std_queue->front());
std_queue->pop();
// update overall number of pop
popNo++;
popLock.unlock();
fullCondition.notify_one();
return r;
}
它会起作用吗?
【问题讨论】:
标签: c++ boost stl queue condition-variable