LocklessList.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 <QAtomicPointer>
  27. #include "LocklessAllocator.h"
  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. {
  39. m_allocator = new LocklessAllocatorT<Element>( size );
  40. }
  41. ~LocklessList()
  42. {
  43. delete m_allocator;
  44. }
  45. void push( T value )
  46. {
  47. Element * e = m_allocator->alloc();
  48. e->value = value;
  49. do
  50. {
  51. #if QT_VERSION >= 0x050000
  52. e->next = m_first.loadAcquire();
  53. #else
  54. e->next = m_first;
  55. #endif
  56. }
  57. while( !m_first.testAndSetOrdered( e->next, e ) );
  58. }
  59. Element * popList()
  60. {
  61. return m_first.fetchAndStoreOrdered( NULL );
  62. }
  63. Element * first()
  64. {
  65. #if QT_VERSION >= 0x050000
  66. return m_first.loadAcquire();
  67. #else
  68. return m_first;
  69. #endif
  70. }
  71. void setFirst( Element * e )
  72. {
  73. #if QT_VERSION >= 0x050000
  74. m_first.storeRelease( e );
  75. #else
  76. m_first = e;
  77. #endif
  78. }
  79. void free( Element * e )
  80. {
  81. m_allocator->free( e );
  82. }
  83. private:
  84. QAtomicPointer<Element> m_first;
  85. LocklessAllocatorT<Element> * m_allocator;
  86. } ;
  87. #endif