google base库之simplethread

 

// 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的消息循环接合得比较紧密,后续文章再一一解开。

posted @ 2016-05-02 21:10  寻不可道之道  阅读(478)  评论(0编辑  收藏  举报