关键词搜索

源码搜索 ×
×

tars源码分析之16

发布2022-07-10浏览615次

详情内容

基本线程类,很简单,不需要多说:

  1. #include "util/tc_thread.h"
  2. #include <cerrno>
  3. namespace tars
  4. {
  5. TC_ThreadControl::TC_ThreadControl(pthread_t thread) : _thread(thread)
  6. {
  7. }
  8. TC_ThreadControl::TC_ThreadControl() : _thread(pthread_self())
  9. {
  10. }
  11. void TC_ThreadControl::join()
  12. {
  13. if(pthread_self() == _thread)
  14. {
  15. throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] can't be called in the same thread");
  16. }
  17. void* ignore = 0;
  18. int rc = pthread_join(_thread, &ignore);
  19. if(rc != 0)
  20. {
  21. throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] pthread_join error ", rc);
  22. }
  23. }
  24. void TC_ThreadControl::detach()
  25. {
  26. if(pthread_self() == _thread)
  27. {
  28. throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] can't be called in the same thread");
  29. }
  30. int rc = pthread_detach(_thread);
  31. if(rc != 0)
  32. {
  33. throw TC_ThreadThreadControl_Exception("[TC_ThreadControl::join] pthread_join error", rc);
  34. }
  35. }
  36. pthread_t TC_ThreadControl::id() const
  37. {
  38. return _thread;
  39. }
  40. void TC_ThreadControl::sleep(long millsecond)
  41. {
  42. struct timespec ts;
  43. ts.tv_sec = millsecond / 1000;
  44. ts.tv_nsec = (millsecond % 1000)*1000000;
  45. nanosleep(&ts, 0);
  46. }
  47. void TC_ThreadControl::yield()
  48. {
  49. sched_yield();
  50. }
  51. TC_Thread::TC_Thread() : _running(false),_tid(-1)
  52. {
  53. }
  54. void TC_Thread::threadEntry(TC_Thread *pThread)
  55. {
  56. pThread->_running = true;
  57. {
  58. TC_ThreadLock::Lock sync(pThread->_lock);
  59. pThread->_lock.notifyAll();
  60. }
  61. try
  62. {
  63. pThread->run();
  64. }
  65. catch(...)
  66. {
  67. pThread->_running = false;
  68. throw;
  69. }
  70. pThread->_running = false;
  71. }
  72. TC_ThreadControl TC_Thread::start()
  73. {
  74. TC_ThreadLock::Lock sync(_lock);
  75. if(_running)
  76. {
  77. throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread has start");
  78. }
  79. int ret = pthread_create(&_tid,
  80. 0,
  81. (void *(*)(void *))&threadEntry,
  82. (void *)this);
  83. if(ret != 0)
  84. {
  85. throw TC_ThreadThreadControl_Exception("[TC_Thread::start] thread start error", ret);
  86. }
  87. _lock.wait();
  88. return TC_ThreadControl(_tid);
  89. }
  90. TC_ThreadControl TC_Thread::getThreadControl() const
  91. {
  92. return TC_ThreadControl(_tid);
  93. }
  94. bool TC_Thread::isAlive() const
  95. {
  96. return _running;
  97. }
  98. }

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载