#ifndef _FY_THREAD_H_ #define _FY_THREAD_H_ #include #include #include #include #include #include #include #include namespace base { class thread { public: typedef void (*func_thread_void)(); typedef void (*func_thread_arg1)(void* arg1); struct meta_data { thread* t; func_thread_arg1 func; void* arg; }; thread(base::thread::func_thread_arg1 func, void* arg) { int ret; joinable_ = true; struct meta_data* meta = new meta_data(); meta->t = this; meta->func = func; meta->arg = arg; thread_id_ = -1; ret = pthread_create(&pthread_t_, NULL, base::thread::func_thread_wrapper, meta); if (ret != 0) { LOGE("create thread error, errno = %d", errno); } } static std::string name() { char name[64] = {0}; prctl(PR_GET_NAME, (unsigned long)name); return name; } void set_name(const char* name64) { prctl(PR_SET_NAME, (unsigned long)name64); } void join() { void* ret_val; int ret = pthread_join(pthread_t_, &ret_val); if (ret != 0) { LOGE("pthread_join failed errno %d", errno); } joinable_ = false; } void detach() { int ret = pthread_detach(pthread_t_); if (ret != 0) { LOGE("pthread_detach failed, ret = %d, errno = %d", ret, errno); } joinable_ = false; } bool joinable() { return joinable_; } size_t id() { return thread_id_; } static size_t current_id() { return syscall(SYS_gettid); } virtual ~thread() { if (joinable()) { detach(); int ret_val; pthread_exit(&ret_val); } } private: static void* func_thread_wrapper(void *arg) { LOGD("current thread id %u", thread::current_id()); base::thread::meta_data* meta = (base::thread::meta_data*)arg; meta->t->thread_id_ = thread::current_id(); meta->func(meta->arg); delete meta; return NULL; } pthread_t pthread_t_; bool joinable_; size_t thread_id_; }; } /* namespace base */ #endif