tc_thread_cond.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #ifndef _TC_THREAD_COND_H
  17. #define _TC_THREAD_COND_H
  18. #include <cerrno>
  19. #include <iostream>
  20. #include <condition_variable>
  21. #include "util/tc_platform.h"
  22. #include "util/tc_ex.h"
  23. namespace tars
  24. {
  25. /////////////////////////////////////////////////
  26. /**
  27. * @file tc_thread_cond.h
  28. * @brief 线程锁以及条件变量类(兼容TARS4.x版本, 底层直接封装了c++11, 从而跨平台兼容)
  29. *
  30. * @author jarodruan@upchina.com
  31. */
  32. /////////////////////////////////////////////////
  33. class TC_ThreadMutex;
  34. /**
  35. * @brief 线程信号条件类, 所有锁可以在上面等待信号发生
  36. *
  37. * 和TC_ThreadMutex、TC_ThreadRecMutex配合使用,
  38. *
  39. * 通常不直接使用,而是使用TC_ThreadLock/TC_ThreadRecLock;
  40. */
  41. class TC_ThreadCond
  42. {
  43. public:
  44. /**
  45. * @brief 构造函数
  46. */
  47. TC_ThreadCond();
  48. /**
  49. * @brief 析构函数
  50. */
  51. ~TC_ThreadCond();
  52. /**
  53. * @brief 发送信号, 等待在该条件上的一个线程会醒
  54. */
  55. void signal();
  56. /**
  57. * @brief 等待在该条件的所有线程都会醒
  58. */
  59. void broadcast();
  60. /**
  61. * @brief 无限制等待.
  62. *
  63. * @param M
  64. */
  65. template<typename Mutex>
  66. void wait(const Mutex& mutex) const
  67. {
  68. _cond.wait(mutex._mutex);
  69. }
  70. /**
  71. * @brief 等待时间.
  72. *
  73. * @param M
  74. * @return bool, false表示超时, true:表示有事件来了
  75. */
  76. template<typename Mutex>
  77. bool timedWait(const Mutex& mutex, int millsecond) const
  78. {
  79. if(_cond.wait_for(mutex._mutex, std::chrono::milliseconds(millsecond))==std::cv_status::timeout)
  80. {
  81. return false;
  82. }
  83. return true;
  84. }
  85. protected:
  86. // Not implemented; prevents accidental use.
  87. TC_ThreadCond(const TC_ThreadCond&);
  88. TC_ThreadCond& operator=(const TC_ThreadCond&);
  89. private:
  90. /**
  91. * 线程条件
  92. */
  93. mutable std::condition_variable_any _cond;
  94. };
  95. }
  96. #endif