jack2 codebase
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.

154 lines
2.7KB

  1. /*
  2. Copyright (C) 2006 Grame
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  14. Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
  15. grame@grame.fr
  16. */
  17. #ifndef __JackMutex__
  18. #define __JackMutex__
  19. #ifdef WIN32
  20. #include <windows.h>
  21. #else
  22. #include <pthread.h>
  23. #endif
  24. #include<assert.h>
  25. namespace Jack
  26. {
  27. class JackMutex
  28. {
  29. private:
  30. #ifdef WIN32
  31. HANDLE fMutex;
  32. #else
  33. pthread_mutex_t fMutex;
  34. #endif
  35. public:
  36. #ifdef WIN32
  37. JackMutex()
  38. {
  39. fMutex = CreateMutex(0, FALSE, 0);
  40. }
  41. virtual ~JackMutex()
  42. {
  43. CloseHandle(fMutex);
  44. }
  45. void Lock()
  46. {
  47. DWORD dwWaitResult = WaitForSingleObject(fMutex, INFINITE);
  48. }
  49. void Unlock()
  50. {
  51. ReleaseMutex(fMutex);
  52. }
  53. #else
  54. JackMutex()
  55. {
  56. // Use recursive mutex
  57. pthread_mutexattr_t mutex_attr;
  58. assert(pthread_mutexattr_init(&mutex_attr) == 0);
  59. assert(pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE) == 0);
  60. assert(pthread_mutex_init(&fMutex, &mutex_attr) == 0);
  61. }
  62. virtual ~JackMutex()
  63. {
  64. pthread_mutex_destroy(&fMutex);
  65. }
  66. void Lock()
  67. {
  68. pthread_mutex_lock(&fMutex);
  69. }
  70. void Unlock()
  71. {
  72. pthread_mutex_unlock(&fMutex);
  73. }
  74. #endif
  75. };
  76. class JackLockAble
  77. {
  78. private:
  79. JackMutex fMutex;
  80. public:
  81. JackLockAble()
  82. {}
  83. virtual ~JackLockAble()
  84. {}
  85. void Lock()
  86. {
  87. fMutex.Lock();
  88. }
  89. void Unlock()
  90. {
  91. fMutex.Unlock();
  92. }
  93. };
  94. class JackLock
  95. {
  96. private:
  97. JackLockAble* fObj;
  98. public:
  99. JackLock(JackLockAble* obj): fObj(obj)
  100. {
  101. fObj->Lock();
  102. }
  103. JackLock(const JackLockAble* obj): fObj((JackLockAble*)obj)
  104. {
  105. fObj->Lock();
  106. }
  107. virtual ~JackLock()
  108. {
  109. fObj->Unlock();
  110. }
  111. };
  112. } // namespace
  113. #endif