Semaphore.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Author : Bruce Liang
  5. * Website : https://github.com/ldcsaa
  6. * Project : https://github.com/ldcsaa/HP-Socket
  7. * Blog : http://www.cnblogs.com/ldcsaa
  8. * Wiki : http://www.oschina.net/p/hp-socket
  9. * QQ Group : 44636872, 75375912
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. #pragma once
  24. #include "hpsocket/GlobalDef.h"
  25. #include "CriSec.h"
  26. #include <condition_variable>
  27. using namespace std;
  28. class CSEM
  29. {
  30. public:
  31. void Wait()
  32. {
  33. CMutexLock2 lock(m_mtx);
  34. m_cv.wait(lock);
  35. }
  36. template<typename _Predicate>
  37. void Wait(_Predicate p)
  38. {
  39. CMutexLock2 lock(m_mtx);
  40. m_cv.wait(lock, p);
  41. }
  42. template<typename _Rep, typename _Period>
  43. cv_status WaitFor(const chrono::duration<_Rep, _Period>& t)
  44. {
  45. CMutexLock2 lock(m_mtx);
  46. return m_cv.wait_for(lock, t);
  47. }
  48. cv_status WaitFor(DWORD dwMilliseconds)
  49. {
  50. return WaitFor(chrono::milliseconds(dwMilliseconds));
  51. }
  52. template<typename _Rep, typename _Period, typename _Predicate>
  53. bool WaitFor(const chrono::duration<_Rep, _Period>& t, _Predicate p)
  54. {
  55. CMutexLock2 lock(m_mtx);
  56. return m_cv.wait_for(lock, t, p);
  57. }
  58. template<typename _Predicate>
  59. bool WaitFor(DWORD dwMilliseconds, _Predicate p)
  60. {
  61. if(IS_INFINITE(dwMilliseconds))
  62. {
  63. Wait(p);
  64. return true;
  65. }
  66. return WaitFor(chrono::milliseconds(dwMilliseconds), p);
  67. }
  68. void NotifyOne()
  69. {
  70. m_cv.notify_one();
  71. }
  72. void NotifyAll()
  73. {
  74. m_cv.notify_all();
  75. }
  76. void SyncNotifyOne()
  77. {
  78. CMutexLock2 lock(m_mtx);
  79. NotifyOne();
  80. }
  81. void SyncNotifyAll()
  82. {
  83. CMutexLock2 lock(m_mtx);
  84. NotifyAll();
  85. }
  86. private:
  87. CMTX m_mtx;
  88. condition_variable m_cv;
  89. DECLARE_NO_COPY_CLASS(CSEM)
  90. DECLARE_PUBLIC_DEFAULT_CONSTRUCTOR(CSEM)
  91. };
  92. using CCVLock = CSEM;