多线程Thread篇


主要文件 core/os/thread.hcore/os/thread.cpp

  1. 线程类 thread 声明原型
   typedef void (*ThreadCreateCallback)(void *p_userdata);

   class Thread {
   public:
    
    // 优先权声明
   enum Priority {

    PRIORITY_LOW,
    PRIORITY_NORMAL,
    PRIORITY_HIGH
   };

    //默认 normal优先级
   struct Settings {
    Priority priority;
    Settings() { priority = PRIORITY_NORMAL; }
   };

   typedef uint64_t ID;

   protected:
   static Thread *(*create_func)(ThreadCreateCallback p_callback, void *, const Settings &);
   static ID (*get_thread_id_func)();
   static void (*wait_to_finish_func)(Thread *);
   static Error (*set_name_func)(const String &);

   friend class Main;

   static ID _main_thread_id;

   Thread() {}

   public:
   virtual ID get_id() const = 0;

   static Error set_name(const String &p_name);
   _FORCE_INLINE_ static ID get_main_id() { return _main_thread_id; } ///< get the ID of the main thread
   static ID get_caller_id(); ///< get the ID of the caller function ID
   static void wait_to_finish(Thread *p_thread); ///< waits until thread is finished, and deallocates it.
   static Thread *create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings = Settings()); ///< Static function to create a thread, will call p_callback

   virtual ~Thread() {}
   };
  1. Thread实现
   // 初始化静态 createcallback = null
   Thread *(*Thread::create_func)(ThreadCreateCallback, void *, const Settings &) = nullptr;
   //初始化 getthreadidcallback = null
   Thread::ID (*Thread::get_thread_id_func)() = nullptr;
   //初始化 waitfinishcallback = null
   void (*Thread::wait_to_finish_func)(Thread *) = nullptr;
   //初始化 setnamecallback = null
   Error (*Thread::set_name_func)(const String &) = nullptr;
   //初始化 mainthread = 0
   Thread::ID Thread::_main_thread_id = 0;
   
   Thread::ID Thread::get_caller_id() {
    if (get_thread_id_func) {
        return get_thread_id_func();
    }
    return 0;
   }
   
   Thread *Thread::create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings) {
    if (create_func) {
        return create_func(p_callback, p_user, p_settings);
    }
    return nullptr;
   }
   
   void Thread::wait_to_finish(Thread *p_thread) {
    if (wait_to_finish_func) {
        wait_to_finish_func(p_thread);
    }
   }
   
   Error Thread::set_name(const String &p_name) {
    if (set_name_func) {
        return set_name_func(p_name);
    }
   
    return ERR_UNAVAILABLE;
   }

文章作者: lyg
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 lyg !
  目录