MultiThread_Containers.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #pragma once
  9. #include "StlUtils.h"
  10. #include <queue>
  11. #include <set>
  12. #include <algorithm>
  13. namespace CryMT
  14. {
  15. //////////////////////////////////////////////////////////////////////////
  16. // Thread Safe wrappers on the standard STL containers.
  17. //////////////////////////////////////////////////////////////////////////
  18. //////////////////////////////////////////////////////////////////////////
  19. // Multi-Thread safe queue container.
  20. //////////////////////////////////////////////////////////////////////////
  21. template <class T, class Alloc = std::allocator<T> >
  22. class queue
  23. {
  24. public:
  25. typedef T value_type;
  26. typedef std::queue<T, std::deque<T, Alloc>> container_type;
  27. typedef AZStd::lock_guard<AZStd::recursive_mutex> AutoLock;
  28. //////////////////////////////////////////////////////////////////////////
  29. // std::queue interface
  30. //////////////////////////////////////////////////////////////////////////
  31. const T& front() const { AutoLock lock(m_cs); return v.front(); };
  32. const T& back() const { AutoLock lock(m_cs); return v.back(); }
  33. void push(const T& x) { AutoLock lock(m_cs); return v.push(x); };
  34. void reserve(const size_t n) { AutoLock lock(m_cs); v.reserve(n); };
  35. AZStd::recursive_mutex& get_lock() const { return m_cs; }
  36. bool empty() const { AutoLock lock(m_cs); return v.empty(); }
  37. int size() const { AutoLock lock(m_cs); return v.size(); }
  38. void clear() { AutoLock lock(m_cs); v.clear(); }
  39. void free_memory() { AutoLock lock(m_cs); stl::free_container(v); }
  40. template <class Func>
  41. void sort(const Func& compare_less) { AutoLock lock(m_cs); std::sort(v.begin(), v.end(), compare_less); }
  42. //////////////////////////////////////////////////////////////////////////
  43. bool try_pop(T& returnValue)
  44. {
  45. AutoLock lock(m_cs);
  46. if (!v.empty())
  47. {
  48. returnValue = v.front();
  49. v.pop();
  50. return true;
  51. }
  52. return false;
  53. };
  54. private:
  55. container_type v;
  56. mutable AZStd::recursive_mutex m_cs;
  57. };
  58. }; // namespace CryMT
  59. namespace stl
  60. {
  61. template <typename T>
  62. void free_container(CryMT::queue<T>& v)
  63. {
  64. v.free_memory();
  65. }
  66. }