ThreadSafeFreeList.h 909 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #pragma once
  2. #include "Baselib.h"
  3. #include "Cpp/mpmc_node_stack.h"
  4. namespace il2cpp
  5. {
  6. namespace utils
  7. {
  8. typedef baselib::mpmc_node ThreadSafeFreeListNode;
  9. /// Lockless allocator that keeps instances of T on a free list.
  10. ///
  11. /// T must be derived from ThreadSafeFreeListNode.
  12. ///
  13. template<typename T>
  14. struct ThreadSafeFreeList
  15. {
  16. T* Allocate()
  17. {
  18. T* instance = m_NodePool.try_pop_back();
  19. if (!instance)
  20. instance = new T();
  21. return instance;
  22. }
  23. void Release(T* instance)
  24. {
  25. m_NodePool.push_back(instance);
  26. }
  27. ~ThreadSafeFreeList()
  28. {
  29. T* instance;
  30. while ((instance = m_NodePool.try_pop_back()) != NULL)
  31. delete instance;
  32. }
  33. private:
  34. baselib::mpmc_node_stack<T> m_NodePool;
  35. };
  36. } /* utils */
  37. } /* il2cpp */