量化交易之One Piece篇 - 线程安全队列- ThreadSafeQueue
  W17cxBGSpUYm 2023年11月15日 84 0


#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;
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  8Tw5Riv1mGFK   2024年05月01日   78   0   0 C++
  BYaHC1OPAeY4   2024年05月08日   56   0   0 C++
  yZdUbUDB8h5t   2024年05月05日   43   0   0 C++
  oXKBKZoQY2lx   2024年05月17日   57   0   0 C++
W17cxBGSpUYm