ThreadSafeFreeList.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #pragma once
  2. #include "os/Unity/AtomicQueue.h"
  3. namespace il2cpp
  4. {
  5. namespace utils
  6. {
  7. struct ThreadSafeFreeListNode
  8. {
  9. ThreadSafeFreeListNode* nextFreeListNode;
  10. ThreadSafeFreeListNode()
  11. : nextFreeListNode(NULL) {}
  12. };
  13. /// Lockless allocator that keeps instances of T on a free list.
  14. ///
  15. /// T must be derived from ThreadSafeFreeListNode.
  16. ///
  17. /// NOTE: T must have sizeof(T) >= sizeof(void*).
  18. template<typename T>
  19. struct ThreadSafeFreeList
  20. {
  21. T* Allocate()
  22. {
  23. T* instance = reinterpret_cast<T*>(m_FreeList.Pop());
  24. if (!instance)
  25. instance = new T();
  26. return instance;
  27. }
  28. void Release(T* instance)
  29. {
  30. ThreadSafeFreeListNode* node = static_cast<ThreadSafeFreeListNode*>(instance);
  31. m_FreeList.Push(reinterpret_cast<il2cpp::os::AtomicNode*>(node));
  32. }
  33. ~ThreadSafeFreeList()
  34. {
  35. T* instance;
  36. while ((instance = reinterpret_cast<T*>(m_FreeList.Pop())) != NULL)
  37. delete instance;
  38. }
  39. private:
  40. ALIGN_TYPE(64) il2cpp::os::AtomicStack m_FreeList;
  41. };
  42. } /* utils */
  43. } /* il2cpp */