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