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.

105 lines
2.0KB

  1. /***************************************************/
  2. /*! \class Mutex
  3. \brief STK mutex class.
  4. This class provides a uniform interface for
  5. cross-platform mutex use. On Linux and IRIX
  6. systems, the pthread library is used. Under
  7. Windows, critical sections are used.
  8. by Perry R. Cook and Gary P. Scavone, 1995--2017.
  9. */
  10. /***************************************************/
  11. #include "Mutex.h"
  12. namespace stk {
  13. Mutex :: Mutex()
  14. {
  15. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  16. pthread_mutex_init(&mutex_, NULL);
  17. pthread_cond_init(&condition_, NULL);
  18. #elif defined(__OS_WINDOWS__)
  19. InitializeCriticalSection(&mutex_);
  20. condition_ = CreateEvent(NULL, // no security
  21. true, // manual-reset
  22. false, // non-signaled initially
  23. NULL); // unnamed
  24. #endif
  25. }
  26. Mutex :: ~Mutex()
  27. {
  28. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  29. pthread_mutex_destroy(&mutex_);
  30. pthread_cond_destroy(&condition_);
  31. #elif defined(__OS_WINDOWS__)
  32. DeleteCriticalSection(&mutex_);
  33. CloseHandle( condition_ );
  34. #endif
  35. }
  36. void Mutex :: lock()
  37. {
  38. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  39. pthread_mutex_lock(&mutex_);
  40. #elif defined(__OS_WINDOWS__)
  41. EnterCriticalSection(&mutex_);
  42. #endif
  43. }
  44. void Mutex :: unlock()
  45. {
  46. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  47. pthread_mutex_unlock(&mutex_);
  48. #elif defined(__OS_WINDOWS__)
  49. LeaveCriticalSection(&mutex_);
  50. #endif
  51. }
  52. void Mutex :: wait()
  53. {
  54. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  55. pthread_cond_wait(&condition_, &mutex_);
  56. #elif defined(__OS_WINDOWS__)
  57. WaitForMultipleObjects(1, &condition_, false, INFINITE);
  58. #endif
  59. }
  60. void Mutex :: signal()
  61. {
  62. #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__))
  63. pthread_cond_signal(&condition_);
  64. #elif defined(__OS_WINDOWS__)
  65. SetEvent( condition_ );
  66. #endif
  67. }
  68. } // stk namespace