Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
2.4KB

  1. /*
  2. * Carla Mutex
  3. * Copyright (C) 2013 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the GPL.txt file
  16. */
  17. #ifndef __CARLA_MUTEX_HPP__
  18. #define __CARLA_MUTEX_HPP__
  19. #include "CarlaJuceUtils.hpp"
  20. // #define CPP11_MUTEX
  21. #ifdef CPP11_MUTEX
  22. # include <mutex>
  23. #else
  24. # include <pthread.h>
  25. #endif
  26. // -------------------------------------------------
  27. // CarlaMutex class
  28. class CarlaMutex
  29. {
  30. public:
  31. CarlaMutex()
  32. : fTryLockWasCalled(false)
  33. {
  34. #ifndef CPP11_MUTEX
  35. pthread_mutex_init(&pmutex, nullptr);
  36. #endif
  37. }
  38. ~CarlaMutex()
  39. {
  40. #ifndef CPP11_MUTEX
  41. pthread_mutex_destroy(&pmutex);
  42. #endif
  43. }
  44. void lock()
  45. {
  46. #ifdef CPP11_MUTEX
  47. cmutex.lock();
  48. #else
  49. pthread_mutex_lock(&pmutex);
  50. #endif
  51. }
  52. bool tryLock()
  53. {
  54. fTryLockWasCalled = true;
  55. #ifdef CPP11_MUTEX
  56. return cmutex.try_lock();
  57. #else
  58. return (pthread_mutex_trylock(&pmutex) == 0);
  59. #endif
  60. }
  61. void unlock()
  62. {
  63. #ifdef CPP11_MUTEX
  64. cmutex.unlock();
  65. #else
  66. pthread_mutex_unlock(&pmutex);
  67. #endif
  68. }
  69. bool wasTryLockCalled()
  70. {
  71. const bool ret = fTryLockWasCalled;
  72. fTryLockWasCalled = false;
  73. return ret;
  74. }
  75. class ScopedLocker
  76. {
  77. public:
  78. ScopedLocker(CarlaMutex& mutex)
  79. : fMutex(mutex)
  80. {
  81. fMutex.lock();
  82. }
  83. ~ScopedLocker()
  84. {
  85. fMutex.unlock();
  86. }
  87. private:
  88. CarlaMutex& fMutex;
  89. CARLA_PREVENT_HEAP_ALLOCATION
  90. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ScopedLocker)
  91. };
  92. private:
  93. #ifdef CPP11_MUTEX
  94. std::mutex cmutex;
  95. #else
  96. pthread_mutex_t pmutex;
  97. #endif
  98. bool fTryLockWasCalled;
  99. CARLA_PREVENT_HEAP_ALLOCATION
  100. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaMutex)
  101. };
  102. // -------------------------------------------------
  103. #endif // __CARLA_MUTEX_HPP__