#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <shared_mutex>
template<typename T>
class ThreadSafeQueue {
private:
std::queue<T> queue_;
mutable std::mutex mutex_;
std::condition_variable cond_;
public:
void Push(const T& value) {
{
std::unique_lock<std::mutex> lock(mutex_);
queue_.push(value);
}
cond_.notify_one(); // 通知等待中的消费者
}
T Pop() {
std::unique_lock<std::mutex> lock(mutex_);
cond_.wait(lock, [this] { return !queue_.empty(); }); // 等待直到队列非空
T value = queue_.front();
queue_.pop();
return value;
}
bool Empty() const {
std::shared_lock<std::mutex> lock(mutex_);
return queue_.empty();
}
};
#include <memory>
#include <onepiece/datacore/DataCore.h>
#include <memory>
#include <thread>
#include <onepiece/templates/ThreadSafeQueue.h>
using namespace std;
int main(int argc, const char *argv[]) {
ThreadSafeQueue<int> queue;
// 生产者线程
std::thread producerThread([&queue] {
for (int i = 1; i <= 5; ++i) {
queue.Push(i);
std::this_thread::sleep_for(std::chrono::seconds(1));
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
// 消费者线程
std::thread consumerThread([&queue] {
for (int i = 1; i <= 5; ++i) {
int value = queue.Pop();
std::cout << "Consumed: " << value << std::endl;
}
});
producerThread.join();
consumerThread.join();
return 0;
}