ZBLOG

#include #include template class LockFreeQueue { public: LockFreeQueue() : head_(new Node), tail_(head_.load()) {} ~LockFreeQueue() { while (Node* const old_head = head_->next_) { delete head_; ...

#include #include #include

template class LockFreeQueue { public:

  1. LockFreeQueue() : head_(new Node), tail_(head_.load()) {}
  2. ~LockFreeQueue() {
  3. while (Node* const old_head = head_->next_) {
  4. delete head_;
  5. head_ = old_head;
  6. }
  7. delete head_;
  8. }
  9. void push(const T& value) {
  10. auto new_node = std::make_unique<Node>(value);
  11. Node* old_tail = tail_.exchange(new_node.get(), std::memory_order_acq_rel);
  12. old_tail->next_.store(new_node.release(), std::memory_order_release);
  13. size_.fetch_add(1, std::memory_order_release);
  14. }
  15. bool try_pop(T& value) {
  16. Node* old_head = head_.load(std::memory_order_relaxed);
  17. for (;;) {
  18. Node* const new_head = old_head->next_.load();
  19. if (new_head == nullptr) {
  20. return false;
  21. }
  22. if (head_.compare_exchange_weak(old_head, new_head, std::memory_order_acquire)) {
  23. value = new_head->value_;
  24. size_.fetch_sub(1, std::memory_order_release);
  25. delete old_head;
  26. return true;
  27. }
  28. }
  29. }
  30. bool empty() const {
  31. return size_.load(std::memory_order_acquire) == 0;
  32. }

private:

  1. struct Node {
  2. T value_;
  3. std::atomic<Node*> next_;
  4. Node() : next_(nullptr) {}
  5. explicit Node(const T& value) : value_(value), next_(nullptr) {}
  6. };
  7. std::atomic<Node*> head_;
  8. std::atomic<Node*> tail_;
  9. std::atomic<size_t> size_{0};

};

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?