我在C ++中使用定时功能实现多线程队列,即pop
和push
可以将超时作为额外参数。
基本代码如下所示。
template <typename T>
class Queue
{
public:
Queue() = default;
// Usage of a mutex makes the Queue class neither copyable nor movable
Queue(const Queue&) = delete;
Queue& operator=(const Queue&) = delete;
T Pop(const std::chrono::microseconds& micro_secs=std::chrono::microseconds::max())
{
std::unique_lock<std::mutex> lock(mutex_);
if (!cond_var_.wait_for(lock, micro_secs, [this]() { return !queue_.empty(); }))
{
// TODO: throw
}
auto item = queue_.front();
queue_.pop();
return item;
}
void Push(T& item, const std::chrono::microseconds& micro_secs=std::chrono::microseconds::max())
{
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
if (!lock.try_lock_for(micro_secs)) // for this std::mutex should be std::timed_mutex.
{
// Couldn't acquire lock during the specified time.
// TODO: throw
}
queue_.push(item);
lock.unlock();
cond_var_.notify_one();
}
private:
std::queue<T> queue_;
std::mutex mutex_;
std::condition_variable cond_var_;
};
对于Pop()
函数,为了使条件变量超时,互斥锁应 std::mutex
。
但是对于Push()
函数获取锁定时超时,互斥锁应该是std::timed_mutex
。如果try_lock_for
中包含的互斥锁满足unique_lock
要求,则TimedLock
有效。
我很高兴听到解决此问题的任何解决方法。
Pop()
要求队列中的互斥为std::mutex
,因为condition_variable::wait_for()
适用于std::mutex
。另一方面,Push()
要求队列中的互斥为std::timed_mutex
。如何通过队列上的单个锁来解决问题,即Queue
类中的单个互斥锁。
提前致谢。