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