example_tc_thread.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. bTerminate = true;
  35. {
  36. TC_ThreadLock::Lock sync(*this);
  37. notifyAll();
  38. }
  39. }
  40. void doSomething()
  41. {
  42. cout << "doSomething" << endl;
  43. }
  44. /**
  45. * 运行
  46. */
  47. protected:
  48. virtual void run()
  49. {
  50. while(!bTerminate)
  51. {
  52. //TODO: your business
  53. doSomething();
  54. {
  55. TC_ThreadLock::Lock sync(*this);
  56. timedWait(1000);
  57. }
  58. }
  59. }
  60. protected:
  61. bool bTerminate;
  62. };
  63. int main(int argc, char *argv[])
  64. {
  65. try
  66. {
  67. MyThread mt;
  68. mt.start();
  69. sleep(5);
  70. mt.terminate();
  71. mt.getThreadControl().join();
  72. }
  73. catch(exception &ex)
  74. {
  75. cout << ex.what() << endl;
  76. }
  77. return 0;
  78. }