ZBLOG

#include #include #include #include template class LockFreeQueue { public: LockFreeQueue() : head_(new Node), tail_(head_.load()) {} ~LockFreeQueue() { while (Nod...

这个队列中使用了Node结构体来表示队列中的节点,如果不想使用Node结构体,可以考虑使用std::atomicstd::shared_ptr<T>来代替。具体实现如下:

  1. #include <atomic>
  2. #include <condition_variable>
  3. #include <iostream>
  4. #include <memory>
  5. #include <thread>
  6. template <typename T>
  7. class LockFreeQueue
  8. {
  9. public:
  10. LockFreeQueue() : head_(std::make_shared<Node>()), tail_(head_.load()) {}
  11. ~LockFreeQueue()
  12. {
  13. while (std::shared_ptr<Node> old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed))
  14. {
  15. head_ = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
  16. }
  17. }
  18. void push(const T &value)
  19. {
  20. auto new_node = std::make_shared<Node>(value);
  21. auto tail = std::atomic_load_explicit(&tail_, std::memory_order_relaxed);
  22. std::atomic_store_explicit(&tail->next_, new_node, std::memory_order_release);
  23. std::atomic_store_explicit(&tail_, new_node, std::memory_order_release);
  24. size_.fetch_add(1, std::memory_order_release);
  25. }
  26. bool try_pop(T &value)
  27. {
  28. auto const old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed);
  29. auto const new_head = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
  30. if (!new_head)
  31. {
  32. return false;
  33. }
  34. value = new_head->value_;
  35. std::atomic_store_explicit(&head_, new_head, std::memory_order_release);
  36. size_.fetch_sub(1, std::memory_order_release);
  37. return true;
  38. }
  39. bool empty() const
  40. {
  41. return std::atomic_load_explicit(&size_, std::memory_order_acquire) == 0;
  42. }
  43. private:
  44. struct Node
  45. {
  46. T value_;
  47. std::shared_ptr<Node> next_;
  48. Node() : next_(nullptr) {}
  49. explicit Node(const T &value) : value_(value), next_(nullptr) {}
  50. };
  51. std::shared_ptr<Node> head_;
  52. std::shared_ptr<Node> tail_;
  53. std::atomic<size_t> size_{0};
  54. std::condition_variable cv_;
  55. };

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1517

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?