thread.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #ifndef _FY_THREAD_H_
  2. #define _FY_THREAD_H_
  3. #include <sys/syscall.h>
  4. #include <sys/types.h>
  5. #include <sys/prctl.h>
  6. #include <unistd.h>
  7. #include <string>
  8. #include <pthread.h>
  9. #include <errno.h>
  10. #include <utils/Log.h>
  11. namespace base {
  12. class thread {
  13. public:
  14. typedef void (*func_thread_void)();
  15. typedef void (*func_thread_arg1)(void* arg1);
  16. struct meta_data {
  17. thread* t;
  18. func_thread_arg1 func;
  19. void* arg;
  20. };
  21. thread(base::thread::func_thread_arg1 func, void* arg) {
  22. int ret;
  23. joinable_ = true;
  24. struct meta_data* meta = new meta_data();
  25. meta->t = this;
  26. meta->func = func;
  27. meta->arg = arg;
  28. thread_id_ = -1;
  29. ret = pthread_create(&pthread_t_, NULL, base::thread::func_thread_wrapper, meta);
  30. if (ret != 0) {
  31. LOGE("create thread error, errno = %d", errno);
  32. }
  33. }
  34. static std::string name() {
  35. char name[64] = {0};
  36. prctl(PR_GET_NAME, (unsigned long)name);
  37. return name;
  38. }
  39. void set_name(const char* name64) {
  40. prctl(PR_SET_NAME, (unsigned long)name64);
  41. }
  42. void join() {
  43. void* ret_val;
  44. int ret = pthread_join(pthread_t_, &ret_val);
  45. if (ret != 0) {
  46. LOGE("pthread_join failed errno %d", errno);
  47. }
  48. joinable_ = false;
  49. }
  50. void detach() {
  51. int ret = pthread_detach(pthread_t_);
  52. if (ret != 0) {
  53. LOGE("pthread_detach failed, ret = %d, errno = %d", ret, errno);
  54. }
  55. joinable_ = false;
  56. }
  57. bool joinable() {
  58. return joinable_;
  59. }
  60. size_t id() {
  61. return thread_id_;
  62. }
  63. static size_t current_id() {
  64. return syscall(SYS_gettid);
  65. }
  66. virtual ~thread() {
  67. if (joinable()) {
  68. detach();
  69. int ret_val;
  70. pthread_exit(&ret_val);
  71. }
  72. }
  73. private:
  74. static void* func_thread_wrapper(void *arg) {
  75. LOGD("current thread id %u", thread::current_id());
  76. base::thread::meta_data* meta = (base::thread::meta_data*)arg;
  77. meta->t->thread_id_ = thread::current_id();
  78. meta->func(meta->arg);
  79. delete meta;
  80. return NULL;
  81. }
  82. pthread_t pthread_t_;
  83. bool joinable_;
  84. size_t thread_id_;
  85. };
  86. } /* namespace base */
  87. #endif