123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- #ifndef _FY_THREAD_H_
- #define _FY_THREAD_H_
- #include <sys/syscall.h>
- #include <sys/types.h>
- #include <sys/prctl.h>
- #include <unistd.h>
- #include <string>
- #include <pthread.h>
- #include <errno.h>
- #include <utils/Log.h>
- 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
|