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 <queue> 46 #include <string> 47 #include <vector> 48 49 #include "base/base_export.h" 50 #include "base/compiler_specific.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 virtual void Start(); 94 virtual void Join(); 95 96 // Subclasses should override the Run method. 97 virtual void Run() = 0; 98 99 // Return the thread id, only valid after Start(). 100 PlatformThreadId tid() { return tid_; } 101 102 // Return True if Start() has ever been called. 103 bool HasBeenStarted(); 104 105 // Return True if Join() has ever been called. 106 bool HasBeenJoined() { return joined_; } 107 108 // Overridden from PlatformThread::Delegate: 109 void ThreadMain() override; 110 111 private: 112 const std::string name_prefix_; 113 std::string name_; 114 const Options options_; 115 PlatformThreadHandle thread_; // PlatformThread handle, reset after Join. 116 WaitableEvent event_; // Signaled if Start() was ever called. 117 PlatformThreadId tid_ = kInvalidThreadId; // The backing thread's id. 118 bool joined_ = false; // True if Join has been called. 119 120 DISALLOW_COPY_AND_ASSIGN(SimpleThread); 121 }; 122 123 // A SimpleThread which delegates Run() to its Delegate. Non-joinable 124 // DelegateSimpleThread are safe to delete after Run() was invoked, their 125 // Delegates are also safe to delete after that point from this class' point of 126 // view (although implementations must of course make sure that Run() will not 127 // use their Delegate's member state after its deletion). 128 class BASE_EXPORT DelegateSimpleThread : public SimpleThread { 129 public: 130 class BASE_EXPORT Delegate { 131 public: 132 virtual ~Delegate() = default; 133 virtual void Run() = 0; 134 }; 135 136 DelegateSimpleThread(Delegate* delegate, 137 const std::string& name_prefix); 138 DelegateSimpleThread(Delegate* delegate, 139 const std::string& name_prefix, 140 const Options& options); 141 142 ~DelegateSimpleThread() override; 143 void Run() override; 144 145 private: 146 Delegate* delegate_; 147 148 DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThread); 149 }; 150 151 // DelegateSimpleThreadPool allows you to start up a fixed number of threads, 152 // and then add jobs which will be dispatched to the threads. This is 153 // convenient when you have a lot of small work that you want done 154 // multi-threaded, but don't want to spawn a thread for each small bit of work. 155 // 156 // You just call AddWork() to add a delegate to the list of work to be done. 157 // JoinAll() will make sure that all outstanding work is processed, and wait 158 // for everything to finish. You can reuse a pool, so you can call Start() 159 // again after you've called JoinAll(). 160 class BASE_EXPORT DelegateSimpleThreadPool 161 : public DelegateSimpleThread::Delegate { 162 public: 163 typedef DelegateSimpleThread::Delegate Delegate; 164 165 DelegateSimpleThreadPool(const std::string& name_prefix, int num_threads); 166 ~DelegateSimpleThreadPool() override; 167 168 // Start up all of the underlying threads, and start processing work if we 169 // have any. 170 void Start(); 171 172 // Make sure all outstanding work is finished, and wait for and destroy all 173 // of the underlying threads in the pool. 174 void JoinAll(); 175 176 // It is safe to AddWork() any time, before or after Start(). 177 // Delegate* should always be a valid pointer, NULL is reserved internally. 178 void AddWork(Delegate* work, int repeat_count); 179 void AddWork(Delegate* work) { 180 AddWork(work, 1); 181 } 182 183 // We implement the Delegate interface, for running our internal threads. 184 void Run() override; 185 186 private: 187 const std::string name_prefix_; 188 int num_threads_; 189 std::vector<DelegateSimpleThread*> threads_; 190 std::queue<Delegate*> delegates_; 191 base::Lock lock_; // Locks delegates_ 192 WaitableEvent dry_; // Not signaled when there is no work to do. 193 194 DISALLOW_COPY_AND_ASSIGN(DelegateSimpleThreadPool); 195 }; 196 197 } // namespace base 198 199 #endif // BASE_THREADING_SIMPLE_THREAD_H_ 200