henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2004 The WebRTC Project Authors. All rights reserved. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license |
| 5 | * that can be found in the LICENSE file in the root of the source |
| 6 | * tree. An additional intellectual property rights grant can be found |
| 7 | * in the file PATENTS. All contributing project authors may |
| 8 | * be found in the AUTHORS file in the root of the source tree. |
| 9 | */ |
| 10 | |
| 11 | #ifndef WEBRTC_BASE_THREAD_H_ |
| 12 | #define WEBRTC_BASE_THREAD_H_ |
| 13 | |
| 14 | #include <algorithm> |
| 15 | #include <list> |
| 16 | #include <string> |
| 17 | #include <vector> |
| 18 | |
| 19 | #if defined(WEBRTC_POSIX) |
| 20 | #include <pthread.h> |
| 21 | #endif |
| 22 | #include "webrtc/base/constructormagic.h" |
fischman@webrtc.org | e5063b1 | 2014-05-23 17:28:50 +0000 | [diff] [blame] | 23 | #include "webrtc/base/event.h" |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 24 | #include "webrtc/base/messagequeue.h" |
| 25 | |
| 26 | #if defined(WEBRTC_WIN) |
| 27 | #include "webrtc/base/win32.h" |
| 28 | #endif |
| 29 | |
| 30 | namespace rtc { |
| 31 | |
| 32 | class Thread; |
| 33 | |
| 34 | class ThreadManager { |
| 35 | public: |
andresp@webrtc.org | 53d9012 | 2015-02-09 14:19:09 +0000 | [diff] [blame] | 36 | static const int kForever = -1; |
| 37 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 38 | ThreadManager(); |
| 39 | ~ThreadManager(); |
| 40 | |
| 41 | static ThreadManager* Instance(); |
| 42 | |
| 43 | Thread* CurrentThread(); |
| 44 | void SetCurrentThread(Thread* thread); |
| 45 | |
| 46 | // Returns a thread object with its thread_ ivar set |
| 47 | // to whatever the OS uses to represent the thread. |
| 48 | // If there already *is* a Thread object corresponding to this thread, |
| 49 | // this method will return that. Otherwise it creates a new Thread |
| 50 | // object whose wrapped() method will return true, and whose |
| 51 | // handle will, on Win32, be opened with only synchronization privileges - |
| 52 | // if you need more privilegs, rather than changing this method, please |
| 53 | // write additional code to adjust the privileges, or call a different |
| 54 | // factory method of your own devising, because this one gets used in |
| 55 | // unexpected contexts (like inside browser plugins) and it would be a |
| 56 | // shame to break it. It is also conceivable on Win32 that we won't even |
| 57 | // be able to get synchronization privileges, in which case the result |
| 58 | // will have a NULL handle. |
| 59 | Thread *WrapCurrentThread(); |
| 60 | void UnwrapCurrentThread(); |
| 61 | |
| 62 | private: |
| 63 | #if defined(WEBRTC_POSIX) |
| 64 | pthread_key_t key_; |
| 65 | #endif |
| 66 | |
| 67 | #if defined(WEBRTC_WIN) |
| 68 | DWORD key_; |
| 69 | #endif |
| 70 | |
| 71 | DISALLOW_COPY_AND_ASSIGN(ThreadManager); |
| 72 | }; |
| 73 | |
| 74 | struct _SendMessage { |
| 75 | _SendMessage() {} |
| 76 | Thread *thread; |
| 77 | Message msg; |
| 78 | bool *ready; |
| 79 | }; |
| 80 | |
| 81 | enum ThreadPriority { |
| 82 | PRIORITY_IDLE = -1, |
| 83 | PRIORITY_NORMAL = 0, |
| 84 | PRIORITY_ABOVE_NORMAL = 1, |
| 85 | PRIORITY_HIGH = 2, |
| 86 | }; |
| 87 | |
| 88 | class Runnable { |
| 89 | public: |
| 90 | virtual ~Runnable() {} |
| 91 | virtual void Run(Thread* thread) = 0; |
| 92 | |
| 93 | protected: |
| 94 | Runnable() {} |
| 95 | |
| 96 | private: |
| 97 | DISALLOW_COPY_AND_ASSIGN(Runnable); |
| 98 | }; |
| 99 | |
| 100 | // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). |
| 101 | |
| 102 | class Thread : public MessageQueue { |
| 103 | public: |
| 104 | explicit Thread(SocketServer* ss = NULL); |
| 105 | // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or |
| 106 | // guarantee Stop() is explicitly called before the subclass is destroyed). |
| 107 | // This is required to avoid a data race between the destructor modifying the |
| 108 | // vtable, and the Thread::PreRun calling the virtual method Run(). |
kwiberg@webrtc.org | 67186fe | 2015-03-09 22:21:53 +0000 | [diff] [blame] | 109 | ~Thread() override; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 110 | |
| 111 | static Thread* Current(); |
| 112 | |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 113 | // Used to catch performance regressions. Use this to disallow blocking calls |
| 114 | // (Invoke) for a given scope. If a synchronous call is made while this is in |
| 115 | // effect, an assert will be triggered. |
| 116 | // Note that this is a single threaded class. |
| 117 | class ScopedDisallowBlockingCalls { |
| 118 | public: |
| 119 | ScopedDisallowBlockingCalls(); |
| 120 | ~ScopedDisallowBlockingCalls(); |
| 121 | private: |
| 122 | Thread* const thread_; |
| 123 | const bool previous_state_; |
| 124 | }; |
| 125 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 126 | bool IsCurrent() const { |
| 127 | return Current() == this; |
| 128 | } |
| 129 | |
| 130 | // Sleeps the calling thread for the specified number of milliseconds, during |
| 131 | // which time no processing is performed. Returns false if sleeping was |
| 132 | // interrupted by a signal (POSIX only). |
| 133 | static bool SleepMs(int millis); |
| 134 | |
| 135 | // Sets the thread's name, for debugging. Must be called before Start(). |
| 136 | // If |obj| is non-NULL, its value is appended to |name|. |
| 137 | const std::string& name() const { return name_; } |
| 138 | bool SetName(const std::string& name, const void* obj); |
| 139 | |
| 140 | // Sets the thread's priority. Must be called before Start(). |
| 141 | ThreadPriority priority() const { return priority_; } |
| 142 | bool SetPriority(ThreadPriority priority); |
| 143 | |
| 144 | // Starts the execution of the thread. |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 145 | bool Start(Runnable* runnable = NULL); |
| 146 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 147 | // Tells the thread to stop and waits until it is joined. |
| 148 | // Never call Stop on the current thread. Instead use the inherited Quit |
| 149 | // function which will exit the base MessageQueue without terminating the |
| 150 | // underlying OS thread. |
| 151 | virtual void Stop(); |
| 152 | |
| 153 | // By default, Thread::Run() calls ProcessMessages(kForever). To do other |
| 154 | // work, override Run(). To receive and dispatch messages, call |
| 155 | // ProcessMessages occasionally. |
| 156 | virtual void Run(); |
| 157 | |
| 158 | virtual void Send(MessageHandler *phandler, uint32 id = 0, |
| 159 | MessageData *pdata = NULL); |
| 160 | |
| 161 | // Convenience method to invoke a functor on another thread. Caller must |
| 162 | // provide the |ReturnT| template argument, which cannot (easily) be deduced. |
| 163 | // Uses Send() internally, which blocks the current thread until execution |
| 164 | // is complete. |
| 165 | // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool); |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 166 | // NOTE: This function can only be called when synchronous calls are allowed. |
| 167 | // See ScopedDisallowBlockingCalls for details. |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 168 | template <class ReturnT, class FunctorT> |
| 169 | ReturnT Invoke(const FunctorT& functor) { |
tommi@webrtc.org | 7c64ed2 | 2015-03-17 14:25:37 +0000 | [diff] [blame^] | 170 | InvokeBegin(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 171 | FunctorMessageHandler<ReturnT, FunctorT> handler(functor); |
| 172 | Send(&handler); |
tommi@webrtc.org | 7c64ed2 | 2015-03-17 14:25:37 +0000 | [diff] [blame^] | 173 | InvokeEnd(); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 174 | return handler.result(); |
| 175 | } |
| 176 | |
| 177 | // From MessageQueue |
kwiberg@webrtc.org | 67186fe | 2015-03-09 22:21:53 +0000 | [diff] [blame] | 178 | void Clear(MessageHandler* phandler, |
| 179 | uint32 id = MQID_ANY, |
| 180 | MessageList* removed = NULL) override; |
| 181 | void ReceiveSends() override; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 182 | |
| 183 | // ProcessMessages will process I/O and dispatch messages until: |
| 184 | // 1) cms milliseconds have elapsed (returns true) |
| 185 | // 2) Stop() is called (returns false) |
| 186 | bool ProcessMessages(int cms); |
| 187 | |
| 188 | // Returns true if this is a thread that we created using the standard |
| 189 | // constructor, false if it was created by a call to |
| 190 | // ThreadManager::WrapCurrentThread(). The main thread of an application |
| 191 | // is generally not owned, since the OS representation of the thread |
| 192 | // obviously exists before we can get to it. |
| 193 | // You cannot call Start on non-owned threads. |
| 194 | bool IsOwned(); |
| 195 | |
| 196 | #if defined(WEBRTC_WIN) |
| 197 | HANDLE GetHandle() const { |
| 198 | return thread_; |
| 199 | } |
| 200 | DWORD GetId() const { |
| 201 | return thread_id_; |
| 202 | } |
| 203 | #elif defined(WEBRTC_POSIX) |
| 204 | pthread_t GetPThread() { |
| 205 | return thread_; |
| 206 | } |
| 207 | #endif |
| 208 | |
fischman@webrtc.org | e5063b1 | 2014-05-23 17:28:50 +0000 | [diff] [blame] | 209 | // Expose private method running() for tests. |
| 210 | // |
| 211 | // DANGER: this is a terrible public API. Most callers that might want to |
| 212 | // call this likely do not have enough control/knowledge of the Thread in |
| 213 | // question to guarantee that the returned value remains true for the duration |
| 214 | // of whatever code is conditionally executing because of the return value! |
| 215 | bool RunningForTest() { return running(); } |
fischman@webrtc.org | e5063b1 | 2014-05-23 17:28:50 +0000 | [diff] [blame] | 216 | |
jiayl@webrtc.org | 3987b6d | 2014-09-24 17:14:05 +0000 | [diff] [blame] | 217 | // Sets the per-thread allow-blocking-calls flag and returns the previous |
jiayl@webrtc.org | 7dfb7fa | 2014-09-29 22:45:55 +0000 | [diff] [blame] | 218 | // value. Must be called on this thread. |
jiayl@webrtc.org | 3987b6d | 2014-09-24 17:14:05 +0000 | [diff] [blame] | 219 | bool SetAllowBlockingCalls(bool allow); |
| 220 | |
henrike@webrtc.org | e30dab7 | 2014-10-09 15:41:40 +0000 | [diff] [blame] | 221 | // These functions are public to avoid injecting test hooks. Don't call them |
| 222 | // outside of tests. |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 223 | // This method should be called when thread is created using non standard |
| 224 | // method, like derived implementation of rtc::Thread and it can not be |
| 225 | // started by calling Start(). This will set started flag to true and |
| 226 | // owned to false. This must be called from the current thread. |
| 227 | bool WrapCurrent(); |
| 228 | void UnwrapCurrent(); |
| 229 | |
henrike@webrtc.org | e30dab7 | 2014-10-09 15:41:40 +0000 | [diff] [blame] | 230 | protected: |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 231 | // Same as WrapCurrent except that it never fails as it does not try to |
| 232 | // acquire the synchronization access of the thread. The caller should never |
| 233 | // call Stop() or Join() on this thread. |
| 234 | void SafeWrapCurrent(); |
| 235 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 236 | // Blocks the calling thread until this thread has terminated. |
| 237 | void Join(); |
| 238 | |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 239 | static void AssertBlockingIsAllowedOnCurrentThread(); |
| 240 | |
| 241 | friend class ScopedDisallowBlockingCalls; |
| 242 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 243 | private: |
| 244 | static void *PreRun(void *pv); |
| 245 | |
| 246 | // ThreadManager calls this instead WrapCurrent() because |
| 247 | // ThreadManager::Instance() cannot be used while ThreadManager is |
| 248 | // being created. |
jiayl@webrtc.org | ba737cb | 2014-09-18 16:45:21 +0000 | [diff] [blame] | 249 | // The method tries to get synchronization rights of the thread on Windows if |
| 250 | // |need_synchronize_access| is true. |
| 251 | bool WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 252 | bool need_synchronize_access); |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 253 | |
fischman@webrtc.org | e5063b1 | 2014-05-23 17:28:50 +0000 | [diff] [blame] | 254 | // Return true if the thread was started and hasn't yet stopped. |
| 255 | bool running() { return running_.Wait(0); } |
| 256 | |
jiayl@webrtc.org | 3987b6d | 2014-09-24 17:14:05 +0000 | [diff] [blame] | 257 | // Processes received "Send" requests. If |source| is not NULL, only requests |
| 258 | // from |source| are processed, otherwise, all requests are processed. |
| 259 | void ReceiveSendsFromThread(const Thread* source); |
| 260 | |
| 261 | // If |source| is not NULL, pops the first "Send" message from |source| in |
| 262 | // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|. |
| 263 | // The caller must lock |crit_| before calling. |
| 264 | // Returns true if there is such a message. |
| 265 | bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg); |
| 266 | |
tommi@webrtc.org | 7c64ed2 | 2015-03-17 14:25:37 +0000 | [diff] [blame^] | 267 | // Used for tracking performance of Invoke calls. |
| 268 | void InvokeBegin(); |
| 269 | void InvokeEnd(); |
| 270 | |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 271 | std::list<_SendMessage> sendlist_; |
| 272 | std::string name_; |
| 273 | ThreadPriority priority_; |
fischman@webrtc.org | e5063b1 | 2014-05-23 17:28:50 +0000 | [diff] [blame] | 274 | Event running_; // Signalled means running. |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 275 | |
| 276 | #if defined(WEBRTC_POSIX) |
| 277 | pthread_t thread_; |
| 278 | #endif |
| 279 | |
| 280 | #if defined(WEBRTC_WIN) |
| 281 | HANDLE thread_; |
| 282 | DWORD thread_id_; |
| 283 | #endif |
| 284 | |
| 285 | bool owned_; |
henrike@webrtc.org | 92a9bac | 2014-07-14 22:03:57 +0000 | [diff] [blame] | 286 | bool blocking_calls_allowed_; // By default set to |true|. |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 287 | |
| 288 | friend class ThreadManager; |
| 289 | |
| 290 | DISALLOW_COPY_AND_ASSIGN(Thread); |
| 291 | }; |
| 292 | |
| 293 | // AutoThread automatically installs itself at construction |
| 294 | // uninstalls at destruction, if a Thread object is |
| 295 | // _not already_ associated with the current OS thread. |
| 296 | |
| 297 | class AutoThread : public Thread { |
| 298 | public: |
| 299 | explicit AutoThread(SocketServer* ss = 0); |
kwiberg@webrtc.org | 67186fe | 2015-03-09 22:21:53 +0000 | [diff] [blame] | 300 | ~AutoThread() override; |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 301 | |
| 302 | private: |
| 303 | DISALLOW_COPY_AND_ASSIGN(AutoThread); |
| 304 | }; |
| 305 | |
| 306 | // Win32 extension for threads that need to use COM |
| 307 | #if defined(WEBRTC_WIN) |
| 308 | class ComThread : public Thread { |
| 309 | public: |
| 310 | ComThread() {} |
| 311 | virtual ~ComThread() { Stop(); } |
| 312 | |
| 313 | protected: |
| 314 | virtual void Run(); |
| 315 | |
| 316 | private: |
| 317 | DISALLOW_COPY_AND_ASSIGN(ComThread); |
| 318 | }; |
| 319 | #endif |
| 320 | |
| 321 | // Provides an easy way to install/uninstall a socketserver on a thread. |
| 322 | class SocketServerScope { |
| 323 | public: |
| 324 | explicit SocketServerScope(SocketServer* ss) { |
| 325 | old_ss_ = Thread::Current()->socketserver(); |
| 326 | Thread::Current()->set_socketserver(ss); |
| 327 | } |
| 328 | ~SocketServerScope() { |
| 329 | Thread::Current()->set_socketserver(old_ss_); |
| 330 | } |
| 331 | |
| 332 | private: |
| 333 | SocketServer* old_ss_; |
| 334 | |
| 335 | DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope); |
| 336 | }; |
| 337 | |
| 338 | } // namespace rtc |
| 339 | |
| 340 | #endif // WEBRTC_BASE_THREAD_H_ |