Home | History | Annotate | Download | only in threading
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 // WARNING: You should probably be using Thread (thread.h) instead.  Thread is
      6 //          Chrome's message-loop based Thread abstraction, and if you are a
      7 //          thread running in the browser, there will likely be assumptions
      8 //          that your thread will have an associated message loop.
      9 //
     10 // This is a simple thread interface that backs to a native operating system
     11 // thread.  You should use this only when you want a thread that does not have
     12 // an associated MessageLoop.  Unittesting is the best example of this.
     13 //
     14 // The simplest interface to use is DelegateSimpleThread, which will create
     15 // a new thread, and execute the Delegate's virtual Run() in this new thread
     16 // until it has completed, exiting the thread.
     17 //
     18 // NOTE: You *MUST* call Join on the thread to clean up the underlying thread
     19 // resources.  You are also responsible for destructing the SimpleThread object.
     20 // It is invalid to destroy a SimpleThread while it is running, or without
     21 // Start() having been called (and a thread never created).  The Delegate
     22 // object should live as long as a DelegateSimpleThread.
     23 //
     24 // Thread Safety: A SimpleThread is not completely thread safe.  It is safe to
     25 // access it from the creating thread or from the newly created thread.  This
     26 // implies that the creator thread should be the thread that calls Join.
     27 //
     28 // Example:
     29 //   class MyThreadRunner : public DelegateSimpleThread::Delegate { ... };
     30 //   MyThreadRunner runner;
     31 //   DelegateSimpleThread thread(&runner, "good_name_here");
     32 //   thread.Start();
     33 //   // Start will return after the Thread has been successfully started and
     34 //   // initialized.  The newly created thread will invoke runner->Run(), and
     35 //   // run until it returns.
     36 //   thread.Join();  // Wait until the thread has exited.  You *MUST* Join!
     37 //   // The SimpleThread object is still valid, however you may not call Join
     38 //   // or Start again.
     39 
     40 #ifndef BASE_THREADING_SIMPLE_THREAD_H_
     41 #define BASE_THREADING_SIMPLE_THREAD_H_
     42 
     43 #include <stddef.h>
     44 
     45 #include <string>
     46 #include <vector>
     47 
     48 #include "base/base_export.h"
     49 #include "base/compiler_specific.h"
     50 #include "base/containers/queue.h"
     51 #include "base/macros.h"
     52 #include "base/synchronization/lock.h"
     53 #include "base/synchronization/waitable_event.h"
     54 #include "base/threading/platform_thread.h"
     55 
     56 namespace base {
     57 
     58 // This is the base SimpleThread.  You can derive from it and implement the
     59 // virtual Run method, or you can use the DelegateSimpleThread interface.
     60 class BASE_EXPORT SimpleThread : public PlatformThread::Delegate {
     61  public:
     62   struct BASE_EXPORT Options {
     63    public:
     64     Options() = default;
     65     explicit Options(ThreadPriority priority_in) : priority(priority_in) {}
     66     ~Options() = default;
     67 
     68     // Allow copies.
     69     Options(const Options& other) = default;
     70     Options& operator=(const Options& other) = default;
     71 
     72     // A custom stack size, or 0 for the system default.
     73     size_t stack_size = 0;
     74 
     75     ThreadPriority priority = ThreadPriority::NORMAL;
     76 
     77     // If false, the underlying thread's PlatformThreadHandle will not be kept
     78     // around and as such the SimpleThread instance will not be Join()able and
     79     // must not be deleted before Run() is invoked. After that, it's up to
     80     // the subclass to determine when it is safe to delete itself.
     81     bool joinable = true;
     82   };
     83 
     84   // Create a SimpleThread.  |options| should be used to manage any specific
     85   // configuration involving the thread creation and management.
     86   // Every thread has a name, in the form of |name_prefix|/TID, for example
     87   // "my_thread/321".  The thread will not be created until Start() is called.
     88   explicit SimpleThread(const std::string& name_prefix);
     89   SimpleThread(const std::string& name_prefix, const Options& options);
     90 
     91   ~SimpleThread() override;
     92 
     93   // Starts the thread and returns only after the thread has started and
     94   // initialized (i.e. ThreadMain() has been called).
     95   void Start();
     96 
     97   // Joins the thread. If StartAsync() was used to start the thread, then this
     98   // first waits for the thread to start cleanly, then it joins.
     99   void Join();
    100 
    101   // Starts the thread, but returns immediately, without waiting for the thread
    102   // to have initialized first (i.e. this does not wait for ThreadMain() to have
    103   // been run first).
    104   void StartAsync();
    105 
    106   // Subclasses should override the Run method.
    107   virtual void Run() = 0;
    108 
    109   // Returns the thread id, only valid after the thread has started. If the
    110   // thread was started using Start(), then this will be valid after the call to
    111   // Start(). If StartAsync() was used to start the thread, then this must not
    112   // be called before HasBeenStarted() returns True.
    113   PlatformThreadId tid();
    114 
    115   // Returns True if the thread has been started and initialized (i.e. if
    116   // ThreadMain() has run). If the thread was started with StartAsync(), but it
    117   // hasn't been initialized yet (i.e. ThreadMain() has not run), then this will
    118   // return False.
    119   bool HasBeenStarted();
    120 
    121   // Returns True if Join() has ever been called.
    122   bool HasBeenJoined() { return joined_; }
    123 
    124   // Returns true if Start() or StartAsync() has been called.
    125   bool HasStartBeenAttempted() { return start_called_; }
    126 
    127   // Overridden from PlatformThread::Delegate:
    128   void ThreadMain() override;
    129 
    130  private:
    131   // This is called just before the thread is started. This is called regardless
    132   // of whether Start() or StartAsync() is used to start the thread.
    133   virtual void BeforeStart() {}
    134 
    135   // This is called just after the thread has been initialized and just before
    136   // Run() is called. This is called on the newly started thread.
    137   virtual void BeforeRun() {}
    138 
    139   // This is called just before the thread is joined. The thread is started and
    140   // has been initialized before this is called.
    141   virtual void BeforeJoin() {}
    142 
    143   const std::string name_prefix_;
    144   std::string name_;
    145   const Options options_;
    146   PlatformThreadHandle thread_;  // PlatformThread handle, reset after Join.
    147   WaitableEvent event_;          // Signaled if Start() was ever called.
    148   PlatformThreadId tid_ = kInvalidThreadId;  // The backing thread's id.
    149   bool joined_ = false;                      // True if Join has been called.
    150   // Set to true when the platform-thread creation has started.
    151   bool start_called_ = false;
    152 
    153   DISALLOW_COPY_AND_ASSIGN(SimpleThread);
    154 };
    155 
    156 // A SimpleThread which delegates Run() to its Delegate. Non-joinable
    157 // DelegateSimpleThread are safe to delete after Run() was invoked, their
    158 // Delegates are also safe to delete after that point from this class' point of
    159 // view (although implementations must of course make sure that Run() will not
    160 // use their Delegate's member state after its deletion).
    161 class BASE_EXPORT DelegateSimpleThread : public SimpleThread {
    162  public:
    163   class BASE_EXPORT Delegate {
    164    public:
    165     virtual ~Delegate() = default;
    166     virtual void Run() = 0;
    167   };
    168 
    169   DelegateSimpleThread(Delegate* delegate,
    170                        const std::string& name_prefix);
    171   DelegateSimpleThread(Delegate* delegate,
    172                        const std::string& name_prefix,
    173                        const Options& options);
    174 
    175   ~DelegateSimpleThread() override;
    176   void Run() override;
    177 
    178  private:
    179   Delegate* delegate_;
    180 
    181   DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThread);
    182 };
    183 
    184 // DelegateSimpleThreadPool allows you to start up a fixed number of threads,
    185 // and then add jobs which will be dispatched to the threads.  This is
    186 // convenient when you have a lot of small work that you want done
    187 // multi-threaded, but don't want to spawn a thread for each small bit of work.
    188 //
    189 // You just call AddWork() to add a delegate to the list of work to be done.
    190 // JoinAll() will make sure that all outstanding work is processed, and wait
    191 // for everything to finish.  You can reuse a pool, so you can call Start()
    192 // again after you've called JoinAll().
    193 class BASE_EXPORT DelegateSimpleThreadPool
    194     : public DelegateSimpleThread::Delegate {
    195  public:
    196   typedef DelegateSimpleThread::Delegate Delegate;
    197 
    198   DelegateSimpleThreadPool(const std::string& name_prefix, int num_threads);
    199   ~DelegateSimpleThreadPool() override;
    200 
    201   // Start up all of the underlying threads, and start processing work if we
    202   // have any.
    203   void Start();
    204 
    205   // Make sure all outstanding work is finished, and wait for and destroy all
    206   // of the underlying threads in the pool.
    207   void JoinAll();
    208 
    209   // It is safe to AddWork() any time, before or after Start().
    210   // Delegate* should always be a valid pointer, NULL is reserved internally.
    211   void AddWork(Delegate* work, int repeat_count);
    212   void AddWork(Delegate* work) {
    213     AddWork(work, 1);
    214   }
    215 
    216   // We implement the Delegate interface, for running our internal threads.
    217   void Run() override;
    218 
    219  private:
    220   const std::string name_prefix_;
    221   int num_threads_;
    222   std::vector<DelegateSimpleThread*> threads_;
    223   base::queue<Delegate*> delegates_;
    224   base::Lock lock_;            // Locks delegates_
    225   WaitableEvent dry_;    // Not signaled when there is no work to do.
    226 
    227   DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThreadPool);
    228 };
    229 
    230 }  // namespace base
    231 
    232 #endif  // BASE_THREADING_SIMPLE_THREAD_H_
    233