BinarySemaphore.hpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) 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. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef ZT_BINARYSEMAPHORE_HPP
  19. #define ZT_BINARYSEMAPHORE_HPP
  20. #include <stdio.h>
  21. #include <stdint.h>
  22. #include <stdlib.h>
  23. #include "Constants.hpp"
  24. #include "NonCopyable.hpp"
  25. #ifdef __WINDOWS__
  26. #include <Windows.h>
  27. namespace ZeroTier {
  28. class BinarySemaphore : NonCopyable
  29. {
  30. public:
  31. BinarySemaphore() throw() { _sem = CreateSemaphore(NULL,0,1,NULL); }
  32. ~BinarySemaphore() { CloseHandle(_sem); }
  33. inline void wait() { WaitForSingleObject(_sem,INFINITE); }
  34. inline void post() { ReleaseSemaphore(_sem,1,NULL); }
  35. private:
  36. HANDLE _sem;
  37. };
  38. } // namespace ZeroTier
  39. #else // !__WINDOWS__
  40. #include <pthread.h>
  41. namespace ZeroTier {
  42. class BinarySemaphore : NonCopyable
  43. {
  44. public:
  45. BinarySemaphore()
  46. {
  47. pthread_mutex_init(&_mh,(const pthread_mutexattr_t *)0);
  48. pthread_cond_init(&_cond,(const pthread_condattr_t *)0);
  49. _f = false;
  50. }
  51. ~BinarySemaphore()
  52. {
  53. pthread_cond_destroy(&_cond);
  54. pthread_mutex_destroy(&_mh);
  55. }
  56. inline void wait()
  57. {
  58. pthread_mutex_lock(const_cast <pthread_mutex_t *>(&_mh));
  59. while (!_f)
  60. pthread_cond_wait(const_cast <pthread_cond_t *>(&_cond),const_cast <pthread_mutex_t *>(&_mh));
  61. _f = false;
  62. pthread_mutex_unlock(const_cast <pthread_mutex_t *>(&_mh));
  63. }
  64. inline void post()
  65. {
  66. pthread_mutex_lock(const_cast <pthread_mutex_t *>(&_mh));
  67. _f = true;
  68. pthread_mutex_unlock(const_cast <pthread_mutex_t *>(&_mh));
  69. pthread_cond_signal(const_cast <pthread_cond_t *>(&_cond));
  70. }
  71. private:
  72. pthread_cond_t _cond;
  73. pthread_mutex_t _mh;
  74. volatile bool _f;
  75. };
  76. } // namespace ZeroTier
  77. #endif // !__WINDOWS__
  78. #endif