HazptrLockFreeLIFO.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <folly/synchronization/Hazptr.h>
  18. namespace folly {
  19. template <typename T, template <typename> class Atom = std::atomic>
  20. class HazptrLockFreeLIFO {
  21. struct Node;
  22. Atom<Node*> head_;
  23. public:
  24. HazptrLockFreeLIFO() : head_(nullptr) {}
  25. ~HazptrLockFreeLIFO() {
  26. Node* next;
  27. for (auto node = head(); node; node = next) {
  28. next = node->next();
  29. node->retire();
  30. }
  31. hazptr_cleanup<Atom>();
  32. }
  33. void push(T val) {
  34. auto node = new Node(val, head());
  35. while (!cas_head(node->next_, node)) {
  36. /* try again */;
  37. }
  38. }
  39. bool pop(T& val) {
  40. hazptr_local<1, Atom> h;
  41. hazptr_holder<Atom>& hptr = h[0];
  42. Node* node;
  43. while (true) {
  44. node = hptr.get_protected(head_);
  45. if (node == nullptr) {
  46. return false;
  47. }
  48. auto next = node->next();
  49. if (cas_head(node, next)) {
  50. break;
  51. }
  52. }
  53. hptr.reset();
  54. val = node->value();
  55. node->retire();
  56. return true;
  57. }
  58. private:
  59. Node* head() {
  60. return head_.load(std::memory_order_acquire);
  61. }
  62. bool cas_head(Node*& expected, Node* newval) {
  63. return head_.compare_exchange_weak(
  64. expected, newval, std::memory_order_acq_rel, std::memory_order_acquire);
  65. }
  66. struct Node : public hazptr_obj_base<Node, Atom> {
  67. T value_;
  68. Node* next_;
  69. Node(T v, Node* n) : value_(v), next_(n) {}
  70. Node* next() {
  71. return next_;
  72. }
  73. T value() {
  74. return value_;
  75. }
  76. };
  77. };
  78. } // namespace folly