標籤:
// This is the base SimpleThread. You can derive from it and implement the// virtual Run method, or you can use the DelegateSimpleThread interface.class BASE_EXPORT SimpleThread : public PlatformThread::Delegate { public: class BASE_EXPORT Options { public: Options() : stack_size_(0) { } ~Options() { } // We use the standard compiler-supplied copy constructor. // A custom stack size, or 0 for the system default. void set_stack_size(size_t size) { stack_size_ = size; } size_t stack_size() const { return stack_size_; } private: size_t stack_size_; }; // Create a SimpleThread. |options| should be used to manage any specific // configuration involving the thread creation and management. // Every thread has a name, in the form of |name_prefix|/TID, for example // "my_thread/321". The thread will not be created until Start() is called. explicit SimpleThread(const std::string& name_prefix); SimpleThread(const std::string& name_prefix, const Options& options); virtual ~SimpleThread(); virtual void Start(); virtual void Join(); // Subclasses should override the Run method. virtual void Run() = 0; // Return the thread name prefix, or "unnamed" if none was supplied. std::string name_prefix() { return name_prefix_; } // Return the completed name including TID, only valid after Start(). std::string name() { return name_; } // Return the thread id, only valid after Start(). PlatformThreadId tid() { return tid_; } // Return True if Start() has ever been called. bool HasBeenStarted(); // Return True if Join() has evern been called. bool HasBeenJoined() { return joined_; } // Overridden from PlatformThread::Delegate: virtual void ThreadMain() OVERRIDE; // Only set priorities with a careful understanding of the consequences. // This is meant for very limited use cases. void SetThreadPriority(ThreadPriority priority) { PlatformThread::SetThreadPriority(thread_, priority); } private: const std::string name_prefix_; std::string name_; const Options options_; PlatformThreadHandle thread_; // PlatformThread handle, invalid after Join! WaitableEvent event_; // Signaled if Start() was ever called. PlatformThreadId tid_; // The backing thread‘s id. bool joined_; // True if Join has been called.};
特別說明,由於需要快速學習,所以,我的文章中有些關於記憶的東西。
這個類相對還是比較簡單,就是對線程的簡單封裝,相比boost的thread簡直不知簡單到哪裡去,不過無所謂,簡單能辦事就可以。
重寫run函數實現自己的邏輯
// Subclasses should override the Run method. virtual void Run() = 0;
值得注意的就是下面這個資料成員
WaitableEvent event_; // Signaled if Start() was ever called.
到是註解中就說得很明白了,必需要start調用了這個event才置信。這個類先不管它吧,後面還在好戲,google的這個架構應當還是挺好用的,必竟是將thread的windows的訊息迴圈接合得比較緊密,後續文章再一一解開。
google base庫之simplethread