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" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 27 | |
| 28 | #if defined(WEBRTC_WIN) |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 29 | #include "rtc_base/win32.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 30 | #endif |
| 31 | |
| 32 | namespace rtc { |
| 33 | |
| 34 | class Thread; |
| 35 | |
| 36 | class ThreadManager { |
| 37 | public: |
| 38 | static const int kForever = -1; |
| 39 | |
| 40 | // Singleton, constructor and destructor are private. |
| 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. |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 59 | Thread* WrapCurrentThread(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 60 | void UnwrapCurrentThread(); |
| 61 | |
| 62 | bool IsMainThread(); |
| 63 | |
| 64 | private: |
| 65 | ThreadManager(); |
| 66 | ~ThreadManager(); |
| 67 | |
| 68 | #if defined(WEBRTC_POSIX) |
| 69 | pthread_key_t key_; |
| 70 | #endif |
| 71 | |
| 72 | #if defined(WEBRTC_WIN) |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 73 | const DWORD key_; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 74 | #endif |
| 75 | |
| 76 | // The thread to potentially autowrap. |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 77 | const PlatformThreadRef main_thread_ref_; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 78 | |
| 79 | RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager); |
| 80 | }; |
| 81 | |
| 82 | struct _SendMessage { |
| 83 | _SendMessage() {} |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 84 | Thread* thread; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 85 | Message msg; |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 86 | bool* ready; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 87 | }; |
| 88 | |
| 89 | class Runnable { |
| 90 | public: |
| 91 | virtual ~Runnable() {} |
| 92 | virtual void Run(Thread* thread) = 0; |
| 93 | |
| 94 | protected: |
| 95 | Runnable() {} |
| 96 | |
| 97 | private: |
| 98 | RTC_DISALLOW_COPY_AND_ASSIGN(Runnable); |
| 99 | }; |
| 100 | |
| 101 | // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). |
| 102 | |
danilchap | 3c6abd2 | 2017-09-06 05:46:29 -0700 | [diff] [blame] | 103 | class RTC_LOCKABLE Thread : public MessageQueue { |
tommi | a8a3515 | 2017-07-13 05:47:25 -0700 | [diff] [blame] | 104 | public: |
tommi | e725159 | 2017-07-14 14:44:46 -0700 | [diff] [blame] | 105 | // DEPRECATED. |
| 106 | // The default constructor should not be used because it hides whether or |
| 107 | // not a socket server will be associated with the thread. Most instances |
| 108 | // of Thread do actually not need one, so please use either of the Create* |
| 109 | // methods to construct an instance of Thread. |
charujain | a117b04 | 2017-07-13 07:06:39 -0700 | [diff] [blame] | 110 | Thread(); |
tommi | e725159 | 2017-07-14 14:44:46 -0700 | [diff] [blame] | 111 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 112 | explicit Thread(SocketServer* ss); |
| 113 | explicit Thread(std::unique_ptr<SocketServer> ss); |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 114 | // Constructors meant for subclasses; they should call DoInit themselves and |
| 115 | // pass false for |do_init|, so that DoInit is called only on the fully |
| 116 | // instantiated class, which avoids a vptr data race. |
| 117 | Thread(SocketServer* ss, bool do_init); |
| 118 | Thread(std::unique_ptr<SocketServer> ss, bool do_init); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 119 | |
| 120 | // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or |
| 121 | // guarantee Stop() is explicitly called before the subclass is destroyed). |
| 122 | // This is required to avoid a data race between the destructor modifying the |
| 123 | // vtable, and the Thread::PreRun calling the virtual method Run(). |
| 124 | ~Thread() override; |
| 125 | |
| 126 | static std::unique_ptr<Thread> CreateWithSocketServer(); |
| 127 | static std::unique_ptr<Thread> Create(); |
| 128 | static Thread* Current(); |
| 129 | |
| 130 | // Used to catch performance regressions. Use this to disallow blocking calls |
| 131 | // (Invoke) for a given scope. If a synchronous call is made while this is in |
| 132 | // effect, an assert will be triggered. |
| 133 | // Note that this is a single threaded class. |
| 134 | class ScopedDisallowBlockingCalls { |
| 135 | public: |
| 136 | ScopedDisallowBlockingCalls(); |
| 137 | ~ScopedDisallowBlockingCalls(); |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 138 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 139 | private: |
| 140 | Thread* const thread_; |
| 141 | const bool previous_state_; |
| 142 | }; |
| 143 | |
| 144 | bool IsCurrent() const; |
| 145 | |
| 146 | // Sleeps the calling thread for the specified number of milliseconds, during |
| 147 | // which time no processing is performed. Returns false if sleeping was |
| 148 | // interrupted by a signal (POSIX only). |
| 149 | static bool SleepMs(int millis); |
| 150 | |
| 151 | // Sets the thread's name, for debugging. Must be called before Start(). |
| 152 | // If |obj| is non-null, its value is appended to |name|. |
| 153 | const std::string& name() const { return name_; } |
| 154 | bool SetName(const std::string& name, const void* obj); |
| 155 | |
| 156 | // Starts the execution of the thread. |
| 157 | bool Start(Runnable* runnable = nullptr); |
| 158 | |
| 159 | // Tells the thread to stop and waits until it is joined. |
| 160 | // Never call Stop on the current thread. Instead use the inherited Quit |
| 161 | // function which will exit the base MessageQueue without terminating the |
| 162 | // underlying OS thread. |
| 163 | virtual void Stop(); |
| 164 | |
| 165 | // By default, Thread::Run() calls ProcessMessages(kForever). To do other |
| 166 | // work, override Run(). To receive and dispatch messages, call |
| 167 | // ProcessMessages occasionally. |
| 168 | virtual void Run(); |
| 169 | |
| 170 | virtual void Send(const Location& posted_from, |
| 171 | MessageHandler* phandler, |
| 172 | uint32_t id = 0, |
| 173 | MessageData* pdata = nullptr); |
| 174 | |
| 175 | // Convenience method to invoke a functor on another thread. Caller must |
| 176 | // provide the |ReturnT| template argument, which cannot (easily) be deduced. |
| 177 | // Uses Send() internally, which blocks the current thread until execution |
| 178 | // is complete. |
| 179 | // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE, |
| 180 | // &MyFunctionReturningBool); |
| 181 | // NOTE: This function can only be called when synchronous calls are allowed. |
| 182 | // See ScopedDisallowBlockingCalls for details. |
| 183 | template <class ReturnT, class FunctorT> |
Karl Wiberg | d6b4819 | 2017-10-16 23:01:06 +0200 | [diff] [blame] | 184 | ReturnT Invoke(const Location& posted_from, FunctorT&& functor) { |
| 185 | FunctorMessageHandler<ReturnT, FunctorT> handler( |
| 186 | std::forward<FunctorT>(functor)); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 187 | InvokeInternal(posted_from, &handler); |
| 188 | return handler.MoveResult(); |
| 189 | } |
| 190 | |
| 191 | // From MessageQueue |
| 192 | void Clear(MessageHandler* phandler, |
| 193 | uint32_t id = MQID_ANY, |
| 194 | MessageList* removed = nullptr) override; |
| 195 | void ReceiveSends() override; |
| 196 | |
| 197 | // ProcessMessages will process I/O and dispatch messages until: |
| 198 | // 1) cms milliseconds have elapsed (returns true) |
| 199 | // 2) Stop() is called (returns false) |
| 200 | bool ProcessMessages(int cms); |
| 201 | |
| 202 | // Returns true if this is a thread that we created using the standard |
| 203 | // constructor, false if it was created by a call to |
| 204 | // ThreadManager::WrapCurrentThread(). The main thread of an application |
| 205 | // is generally not owned, since the OS representation of the thread |
| 206 | // obviously exists before we can get to it. |
| 207 | // You cannot call Start on non-owned threads. |
| 208 | bool IsOwned(); |
| 209 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 210 | // Expose private method IsRunning() for tests. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 211 | // |
| 212 | // DANGER: this is a terrible public API. Most callers that might want to |
| 213 | // call this likely do not have enough control/knowledge of the Thread in |
| 214 | // question to guarantee that the returned value remains true for the duration |
| 215 | // of whatever code is conditionally executing because of the return value! |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 216 | bool RunningForTest() { return IsRunning(); } |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 217 | |
| 218 | // Sets the per-thread allow-blocking-calls flag and returns the previous |
| 219 | // value. Must be called on this thread. |
| 220 | bool SetAllowBlockingCalls(bool allow); |
| 221 | |
| 222 | // These functions are public to avoid injecting test hooks. Don't call them |
| 223 | // outside of tests. |
| 224 | // This method should be called when thread is created using non standard |
| 225 | // method, like derived implementation of rtc::Thread and it can not be |
| 226 | // started by calling Start(). This will set started flag to true and |
| 227 | // owned to false. This must be called from the current thread. |
| 228 | bool WrapCurrent(); |
| 229 | void UnwrapCurrent(); |
| 230 | |
| 231 | protected: |
| 232 | // Same as WrapCurrent except that it never fails as it does not try to |
| 233 | // acquire the synchronization access of the thread. The caller should never |
| 234 | // call Stop() or Join() on this thread. |
| 235 | void SafeWrapCurrent(); |
| 236 | |
| 237 | // Blocks the calling thread until this thread has terminated. |
| 238 | void Join(); |
| 239 | |
| 240 | static void AssertBlockingIsAllowedOnCurrentThread(); |
| 241 | |
| 242 | friend class ScopedDisallowBlockingCalls; |
| 243 | |
| 244 | private: |
| 245 | struct ThreadInit { |
| 246 | Thread* thread; |
| 247 | Runnable* runnable; |
| 248 | }; |
| 249 | |
| 250 | #if defined(WEBRTC_WIN) |
| 251 | static DWORD WINAPI PreRun(LPVOID context); |
| 252 | #else |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 253 | static void* PreRun(void* pv); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 254 | #endif |
| 255 | |
| 256 | // ThreadManager calls this instead WrapCurrent() because |
| 257 | // ThreadManager::Instance() cannot be used while ThreadManager is |
| 258 | // being created. |
| 259 | // The method tries to get synchronization rights of the thread on Windows if |
| 260 | // |need_synchronize_access| is true. |
| 261 | bool WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 262 | bool need_synchronize_access); |
| 263 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 264 | // Return true if the thread is currently running. |
| 265 | bool IsRunning(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 266 | |
| 267 | // Processes received "Send" requests. If |source| is not null, only requests |
| 268 | // from |source| are processed, otherwise, all requests are processed. |
| 269 | void ReceiveSendsFromThread(const Thread* source); |
| 270 | |
| 271 | // If |source| is not null, pops the first "Send" message from |source| in |
| 272 | // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|. |
| 273 | // The caller must lock |crit_| before calling. |
| 274 | // Returns true if there is such a message. |
| 275 | bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg); |
| 276 | |
| 277 | void InvokeInternal(const Location& posted_from, MessageHandler* handler); |
| 278 | |
| 279 | std::list<_SendMessage> sendlist_; |
| 280 | std::string name_; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 281 | |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 282 | // TODO(tommi): Add thread checks for proper use of control methods. |
| 283 | // Ideally we should be able to just use PlatformThread. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 284 | |
| 285 | #if defined(WEBRTC_POSIX) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 286 | pthread_t thread_ = 0; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 287 | #endif |
| 288 | |
| 289 | #if defined(WEBRTC_WIN) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 290 | HANDLE thread_ = nullptr; |
| 291 | DWORD thread_id_ = 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_ |