IlmThreadMutex.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Copyright (c) Contributors to the OpenEXR Project.
  4. //
  5. #ifndef INCLUDED_ILM_THREAD_MUTEX_H
  6. #define INCLUDED_ILM_THREAD_MUTEX_H
  7. //-----------------------------------------------------------------------------
  8. //
  9. // NB: Maintained for backward compatibility with header files only. This
  10. // has been entirely replaced by c++11 and the std::mutex layer
  11. //
  12. //-----------------------------------------------------------------------------
  13. #include "IlmThreadExport.h"
  14. #include "IlmThreadConfig.h"
  15. #include "IlmThreadNamespace.h"
  16. #if ILMTHREAD_THREADING_ENABLED
  17. #include <mutex>
  18. #endif
  19. ILMTHREAD_INTERNAL_NAMESPACE_HEADER_ENTER
  20. #if ILMTHREAD_THREADING_ENABLED
  21. using Mutex ILMTHREAD_DEPRECATED ("replace with std::mutex") = std::mutex;
  22. // unfortunately we can't use std::unique_lock as a replacement for Lock since
  23. // they have different API. Let us deprecate for now and give people a chance
  24. // to clean up their code.
  25. class Lock
  26. {
  27. public:
  28. ILMTHREAD_DEPRECATED ("replace with std::lock_guard or std::unique_lock")
  29. Lock (const Mutex& m, bool autoLock = true):
  30. _mutex (const_cast<Mutex &>(m)), _locked (false)
  31. {
  32. if (autoLock)
  33. {
  34. _mutex.lock();
  35. _locked = true;
  36. }
  37. }
  38. ~Lock ()
  39. {
  40. if (_locked)
  41. _mutex.unlock();
  42. }
  43. Lock (const Lock&) = delete;
  44. Lock &operator= (const Lock&) = delete;
  45. Lock (Lock&&) = delete;
  46. Lock& operator= (Lock&&) = delete;
  47. void acquire ()
  48. {
  49. _mutex.lock();
  50. _locked = true;
  51. }
  52. void release ()
  53. {
  54. _locked = false;
  55. _mutex.unlock();
  56. }
  57. bool locked ()
  58. {
  59. return _locked;
  60. }
  61. private:
  62. Mutex & _mutex;
  63. bool _locked;
  64. };
  65. #endif
  66. ILMTHREAD_INTERNAL_NAMESPACE_HEADER_EXIT
  67. #endif // INCLUDED_ILM_THREAD_MUTEX_H