#include<thread> #include<condition_variable> #include<mutex> #include<queue> #include<stdio.h> template <class T> class ThreadSafeQueue{ public: void Insert(T value); void Popup(T &value); bool Empty() const; private: mutable std::mutex mut_; std::queue<T> que_; std::condition_variable cond_; }; template <class T> void ThreadSafeQueue<T>::Insert(T value){ std::lock_guard<std::mutex> lk(mut_); que_.push(value); cond_.notify_one(); } template <class T> void ThreadSafeQueue<T>::Popup(T &value){ std::unique_lock<std::mutex> lk(mut_); cond_.wait(lk, [this]{return !que_.empty();}); // 如果lamda表达式 [this]{return !que_.empty(); 返回 true, 也就是队列非空,则上锁,继续执行下面的语句; value = que_.front(); // 如果lamda表达式返回False, 也就是队列为空,则解开锁,该线程进入wait,阻塞模式,等待被唤醒 que_.pop(); } template <class T> bool ThreadSafeQueue<T>::Empty() const{ std::lock_guard<std::mutex> lk(mut_); return que_.empty(); } int main(){ ThreadSafeQueue<int> q; int value=1; std::thread t2(&ThreadSafeQueue<int>::Popup, &q, std::ref(value)); // 传引用参数的时候需要使用引用包装器std::ref std::thread t1(&ThreadSafeQueue<int>::Insert, &q, 10); printf("%d\n", value); while(!q.Empty()); t1.join(); t2.join(); printf("%d\n", value); return 0; }