LocklessAllocator.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * LocklessAllocator.h - allocator with lockless alloc and free
  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_ALLOCATOR_H
  25. #define LOCKLESS_ALLOCATOR_H
  26. #include <atomic>
  27. #include <stddef.h>
  28. class LocklessAllocator
  29. {
  30. public:
  31. LocklessAllocator( size_t nmemb, size_t size );
  32. virtual ~LocklessAllocator();
  33. void * alloc();
  34. void free( void * ptr );
  35. private:
  36. char * m_pool;
  37. size_t m_capacity;
  38. size_t m_elementSize;
  39. std::atomic_int * m_freeState;
  40. size_t m_freeStateSets;
  41. std::atomic_int m_available;
  42. std::atomic_int m_startIndex;
  43. } ;
  44. template<typename T>
  45. class LocklessAllocatorT : private LocklessAllocator
  46. {
  47. public:
  48. LocklessAllocatorT( size_t nmemb ) :
  49. LocklessAllocator( nmemb, sizeof( T ) )
  50. {
  51. }
  52. virtual ~LocklessAllocatorT()
  53. {
  54. }
  55. T * alloc()
  56. {
  57. return (T *)LocklessAllocator::alloc();
  58. }
  59. void free( T * ptr )
  60. {
  61. LocklessAllocator::free( ptr );
  62. }
  63. } ;
  64. #endif