LocklessList.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * LocklessList.h - list with lockless push and pop
  3. *
  4. * Copyright (c) 2016 Javier Serrano Polo <javier@jasp.net>
  5. *
  6. * This file is part of LMMS - https://lmms.io
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2 of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public
  19. * License along with this program (see COPYING); if not, write to the
  20. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. * Boston, MA 02110-1301 USA.
  22. *
  23. */
  24. #ifndef LOCKLESS_LIST_H
  25. #define LOCKLESS_LIST_H
  26. #include "LocklessAllocator.h"
  27. #include <atomic>
  28. template<typename T>
  29. class LocklessList
  30. {
  31. public:
  32. struct Element
  33. {
  34. T value;
  35. Element * next;
  36. } ;
  37. LocklessList( size_t size ) :
  38. m_first(nullptr),
  39. m_allocator(new LocklessAllocatorT<Element>(size))
  40. {
  41. }
  42. ~LocklessList()
  43. {
  44. delete m_allocator;
  45. }
  46. void push( T value )
  47. {
  48. Element * e = m_allocator->alloc();
  49. e->value = value;
  50. e->next = m_first.load(std::memory_order_relaxed);
  51. while (!m_first.compare_exchange_weak(e->next, e,
  52. std::memory_order_release,
  53. std::memory_order_relaxed))
  54. {
  55. // Empty loop (compare_exchange_weak updates e->next)
  56. }
  57. }
  58. Element * popList()
  59. {
  60. return m_first.exchange(nullptr);
  61. }
  62. Element * first()
  63. {
  64. return m_first.load(std::memory_order_acquire);
  65. }
  66. void setFirst( Element * e )
  67. {
  68. m_first.store(e, std::memory_order_release);
  69. }
  70. void free( Element * e )
  71. {
  72. m_allocator->free( e );
  73. }
  74. private:
  75. std::atomic<Element*> m_first;
  76. LocklessAllocatorT<Element> * m_allocator;
  77. } ;
  78. #endif