NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
```cpp #include <iostream> #include <mutex> #include <thread> #include <condition_variable> #include <list> template <typename T> class SynQueue { public: SynQueue(size_t maxSize) : maxSize_(maxSize), needStop_(false) {} void put(const T& x) { add(x); } void put(T&& x) { add(std::forward<T>(x)); } void take(std::list<T>& list) { std::unique_lock<std::mutex> lock(mutex_); notEmpty_.wait(lock, [this] { return needStop_ || notEmpty(); }); if (needStop_) return; list = std::move(queue_); notFull_.notify_one(); } void take(T& t) { std::unique_lock<std::mutex> lock(mutex_); notEmpty_.wait(lock, [this] { return needStop_ || notEmpty(); }); if (needStop_) return; t = queue_.front(); queue_.pop_front(); notFull_.notify_one(); } void stop() { { std::lock_guard<std::mutex> lock(mutex_); needStop_ = true; } notFull_.notify_all(); notEmpty_.notify_all(); } private: size_t size() const { std::lock_guard<std::mutex> lock(mutex_); return queue_.size(); } bool notFull() const { bool full = queue_.size() >= maxSize_; if (full) std::cout << "queue is full, need waiting..." << std::endl; return !full; } bool notEmpty() const { bool empty = queue_.empty(); if (empty) std::cout << "queue is empty, need waiting... thread id=" << std::this_thread::get_id() << std::endl; return !empty; } template <typename F> void add(F&& x) { std::unique_lock<std::mutex> lock(mutex_); notFull_.wait(lock, [this] { return needStop_ || notFull(); }); if (needStop_) return; queue_.push_back(std::forward<F>(x)); notEmpty_.notify_one(); } private: std::list<T> queue_; // 缓冲区 std::mutex mutex_; // 互斥量和条件变量结合起来使用 std::condition_variable notEmpty_; // 不为空的条件变量 std::condition_variable notFull_; // 没有满的条件变量 size_t maxSize_; bool needStop_; }; int main(int argc, char** argv) { SynQueue<int> q(10); q.put(2); q.put(3); q.put(4); q.put(1); q.put(9); std::list<int> l; q.take(l); for (auto& i : l) { std::cout << i << std::endl; } return 0; } ```