example_tc_lock.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016 THL 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. #include "util/tc_thread.h"
  17. #include <unistd.h>
  18. #include <iostream>
  19. #include <vector>
  20. using namespace std;
  21. using namespace tars;
  22. class MyThread : public TC_Thread, public TC_ThreadLock
  23. {
  24. public:
  25. MyThread()
  26. {
  27. bTerminate = false;
  28. }
  29. /**
  30. * 结束线程
  31. */
  32. void terminate()
  33. {
  34. //先加锁, 然后设置结束状态, 然后通知其他线程醒过来
  35. Lock sync(*this);
  36. bTerminate = true;
  37. notifyAll();
  38. }
  39. void doSomething()
  40. {
  41. cout << "doSomething" << endl;
  42. }
  43. /**
  44. * 运行
  45. */
  46. protected:
  47. virtual void run()
  48. {
  49. while (!bTerminate)
  50. {
  51. {
  52. Lock sync(*this);
  53. timedWait(10000);
  54. }
  55. if (bTerminate)
  56. {
  57. return;
  58. }
  59. doSomething();
  60. }
  61. }
  62. protected:
  63. bool bTerminate;
  64. };
  65. int main(int argc, char *argv[])
  66. {
  67. try
  68. {
  69. MyThread mt;
  70. mt.start();
  71. mt.terminate();
  72. mt.getThreadControl().join();
  73. }
  74. catch (exception& ex)
  75. {
  76. cout << ex.what() << endl;
  77. }
  78. return 0;
  79. }