实现一个简略的线程安全的队列:
std::condition_variable
用于在多线程编程中进行线程间的同步和通信。它提供了一种机制,允许一个或多个线程在满足特定条件之前等待,并在条件满足时被唤醒。
std::condition_variable
的常用操作:
wait()
: 阻塞当前线程,并在条件变量满足时返回。notify_one()
: 唤醒一个等待该条件变量的线程。notify_all()
: 唤醒所有等待该条件变量的线程。
template <typename T>
class threadsafe_queue {
private:
mutable std::mutex mut;
std::queue<T> data_queue;
std::condition_variable data_cond;
public:
threadsafe_queue() {}
threadsafe_queue(threadsafe_queue const& other) {
std::lock_guard<std::mutex> lk(other.mut);
data_queue = other.data_queue;
}
void push(T new_value) {
std::lock_guard<std::mutex> lk(mut);
data_queue.push(new_value);
data_cond.notify_one();//唤醒data_cond.wait(lk, [this] { return !data_queue.empty(); })此处等待,若其中lamda表达式条件为真,等待结束;
}
void wait_and_pop(T& value) {
std::unique_lock<std::mutex> lk(mut);
data_cond.wait(lk, [this] { return !data_queue.empty(); });
value = data_queue.front();
data_queue.pop();
}
};