Condition.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef __DTC_CONDITION_H__
  17. #define __DTC_CONDITION_H__
  18. #include "algorithm/non_copyable.h"
  19. class condition : private noncopyable {
  20. public:
  21. condition(void)
  22. {
  23. pthread_mutex_init(&m_lock, NULL);
  24. pthread_cond_init(&m_cond, NULL);
  25. }
  26. ~condition(void)
  27. {
  28. pthread_mutex_destroy(&m_lock);
  29. pthread_cond_destroy(&m_cond);
  30. }
  31. void notify_one(void)
  32. {
  33. pthread_cond_signal(&m_cond);
  34. }
  35. void notify_all(void)
  36. {
  37. pthread_cond_broadcast(&m_cond);
  38. }
  39. void wait(void)
  40. {
  41. pthread_cond_wait(&m_cond, &m_lock);
  42. }
  43. void lock(void)
  44. {
  45. pthread_mutex_lock(&m_lock);
  46. }
  47. void unlock(void)
  48. {
  49. pthread_mutex_unlock(&m_lock);
  50. }
  51. private:
  52. pthread_cond_t m_cond;
  53. pthread_mutex_t m_lock;
  54. };
  55. class copedEnterCritical {
  56. public:
  57. copedEnterCritical(condition &c) : m_cond(c)
  58. {
  59. m_cond.lock();
  60. }
  61. ~copedEnterCritical(void)
  62. {
  63. m_cond.unlock();
  64. }
  65. private:
  66. condition &m_cond;
  67. };
  68. class copedLeaveCritical {
  69. public:
  70. copedLeaveCritical(condition &c) : m_cond(c)
  71. {
  72. m_cond.unlock();
  73. }
  74. ~copedLeaveCritical(void)
  75. {
  76. m_cond.lock();
  77. }
  78. private:
  79. condition &m_cond;
  80. };
  81. #endif //__DTC_CONDITION_H__