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> |
| 18 | #include <vector> |
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 |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 23 | #include "rtc_base/constructormagic.h" |
| 24 | #include "rtc_base/event.h" |
| 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. |
| 59 | Thread *WrapCurrentThread(); |
| 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) |
| 73 | DWORD key_; |
| 74 | #endif |
| 75 | |
| 76 | // The thread to potentially autowrap. |
| 77 | PlatformThreadRef main_thread_ref_; |
| 78 | |
| 79 | RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager); |
| 80 | }; |
| 81 | |
| 82 | struct _SendMessage { |
| 83 | _SendMessage() {} |
| 84 | Thread *thread; |
| 85 | Message msg; |
| 86 | bool *ready; |
| 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); |
| 114 | |
| 115 | // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or |
| 116 | // guarantee Stop() is explicitly called before the subclass is destroyed). |
| 117 | // This is required to avoid a data race between the destructor modifying the |
| 118 | // vtable, and the Thread::PreRun calling the virtual method Run(). |
| 119 | ~Thread() override; |
| 120 | |
| 121 | static std::unique_ptr<Thread> CreateWithSocketServer(); |
| 122 | static std::unique_ptr<Thread> Create(); |
| 123 | static Thread* Current(); |
| 124 | |
| 125 | // Used to catch performance regressions. Use this to disallow blocking calls |
| 126 | // (Invoke) for a given scope. If a synchronous call is made while this is in |
| 127 | // effect, an assert will be triggered. |
| 128 | // Note that this is a single threaded class. |
| 129 | class ScopedDisallowBlockingCalls { |
| 130 | public: |
| 131 | ScopedDisallowBlockingCalls(); |
| 132 | ~ScopedDisallowBlockingCalls(); |
| 133 | private: |
| 134 | Thread* const thread_; |
| 135 | const bool previous_state_; |
| 136 | }; |
| 137 | |
| 138 | bool IsCurrent() const; |
| 139 | |
| 140 | // Sleeps the calling thread for the specified number of milliseconds, during |
| 141 | // which time no processing is performed. Returns false if sleeping was |
| 142 | // interrupted by a signal (POSIX only). |
| 143 | static bool SleepMs(int millis); |
| 144 | |
| 145 | // Sets the thread's name, for debugging. Must be called before Start(). |
| 146 | // If |obj| is non-null, its value is appended to |name|. |
| 147 | const std::string& name() const { return name_; } |
| 148 | bool SetName(const std::string& name, const void* obj); |
| 149 | |
| 150 | // Starts the execution of the thread. |
| 151 | bool Start(Runnable* runnable = nullptr); |
| 152 | |
| 153 | // Tells the thread to stop and waits until it is joined. |
| 154 | // Never call Stop on the current thread. Instead use the inherited Quit |
| 155 | // function which will exit the base MessageQueue without terminating the |
| 156 | // underlying OS thread. |
| 157 | virtual void Stop(); |
| 158 | |
| 159 | // By default, Thread::Run() calls ProcessMessages(kForever). To do other |
| 160 | // work, override Run(). To receive and dispatch messages, call |
| 161 | // ProcessMessages occasionally. |
| 162 | virtual void Run(); |
| 163 | |
| 164 | virtual void Send(const Location& posted_from, |
| 165 | MessageHandler* phandler, |
| 166 | uint32_t id = 0, |
| 167 | MessageData* pdata = nullptr); |
| 168 | |
| 169 | // Convenience method to invoke a functor on another thread. Caller must |
| 170 | // provide the |ReturnT| template argument, which cannot (easily) be deduced. |
| 171 | // Uses Send() internally, which blocks the current thread until execution |
| 172 | // is complete. |
| 173 | // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE, |
| 174 | // &MyFunctionReturningBool); |
| 175 | // NOTE: This function can only be called when synchronous calls are allowed. |
| 176 | // See ScopedDisallowBlockingCalls for details. |
| 177 | template <class ReturnT, class FunctorT> |
| 178 | ReturnT Invoke(const Location& posted_from, const FunctorT& functor) { |
| 179 | FunctorMessageHandler<ReturnT, FunctorT> handler(functor); |
| 180 | InvokeInternal(posted_from, &handler); |
| 181 | return handler.MoveResult(); |
| 182 | } |
| 183 | |
| 184 | // From MessageQueue |
| 185 | void Clear(MessageHandler* phandler, |
| 186 | uint32_t id = MQID_ANY, |
| 187 | MessageList* removed = nullptr) override; |
| 188 | void ReceiveSends() override; |
| 189 | |
| 190 | // ProcessMessages will process I/O and dispatch messages until: |
| 191 | // 1) cms milliseconds have elapsed (returns true) |
| 192 | // 2) Stop() is called (returns false) |
| 193 | bool ProcessMessages(int cms); |
| 194 | |
| 195 | // Returns true if this is a thread that we created using the standard |
| 196 | // constructor, false if it was created by a call to |
| 197 | // ThreadManager::WrapCurrentThread(). The main thread of an application |
| 198 | // is generally not owned, since the OS representation of the thread |
| 199 | // obviously exists before we can get to it. |
| 200 | // You cannot call Start on non-owned threads. |
| 201 | bool IsOwned(); |
| 202 | |
| 203 | #if defined(WEBRTC_WIN) |
| 204 | HANDLE GetHandle() const { |
| 205 | return thread_; |
| 206 | } |
| 207 | DWORD GetId() const { |
| 208 | return thread_id_; |
| 209 | } |
| 210 | #elif defined(WEBRTC_POSIX) |
| 211 | pthread_t GetPThread() { |
| 212 | return thread_; |
| 213 | } |
| 214 | #endif |
| 215 | |
| 216 | // Expose private method running() for tests. |
| 217 | // |
| 218 | // DANGER: this is a terrible public API. Most callers that might want to |
| 219 | // call this likely do not have enough control/knowledge of the Thread in |
| 220 | // question to guarantee that the returned value remains true for the duration |
| 221 | // of whatever code is conditionally executing because of the return value! |
| 222 | bool RunningForTest() { return running(); } |
| 223 | |
| 224 | // Sets the per-thread allow-blocking-calls flag and returns the previous |
| 225 | // value. Must be called on this thread. |
| 226 | bool SetAllowBlockingCalls(bool allow); |
| 227 | |
| 228 | // These functions are public to avoid injecting test hooks. Don't call them |
| 229 | // outside of tests. |
| 230 | // This method should be called when thread is created using non standard |
| 231 | // method, like derived implementation of rtc::Thread and it can not be |
| 232 | // started by calling Start(). This will set started flag to true and |
| 233 | // owned to false. This must be called from the current thread. |
| 234 | bool WrapCurrent(); |
| 235 | void UnwrapCurrent(); |
| 236 | |
| 237 | protected: |
| 238 | // Same as WrapCurrent except that it never fails as it does not try to |
| 239 | // acquire the synchronization access of the thread. The caller should never |
| 240 | // call Stop() or Join() on this thread. |
| 241 | void SafeWrapCurrent(); |
| 242 | |
| 243 | // Blocks the calling thread until this thread has terminated. |
| 244 | void Join(); |
| 245 | |
| 246 | static void AssertBlockingIsAllowedOnCurrentThread(); |
| 247 | |
| 248 | friend class ScopedDisallowBlockingCalls; |
| 249 | |
| 250 | private: |
| 251 | struct ThreadInit { |
| 252 | Thread* thread; |
| 253 | Runnable* runnable; |
| 254 | }; |
| 255 | |
| 256 | #if defined(WEBRTC_WIN) |
| 257 | static DWORD WINAPI PreRun(LPVOID context); |
| 258 | #else |
| 259 | static void *PreRun(void *pv); |
| 260 | #endif |
| 261 | |
| 262 | // ThreadManager calls this instead WrapCurrent() because |
| 263 | // ThreadManager::Instance() cannot be used while ThreadManager is |
| 264 | // being created. |
| 265 | // The method tries to get synchronization rights of the thread on Windows if |
| 266 | // |need_synchronize_access| is true. |
| 267 | bool WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 268 | bool need_synchronize_access); |
| 269 | |
| 270 | // Return true if the thread was started and hasn't yet stopped. |
| 271 | bool running() { return running_.Wait(0); } |
| 272 | |
| 273 | // Processes received "Send" requests. If |source| is not null, only requests |
| 274 | // from |source| are processed, otherwise, all requests are processed. |
| 275 | void ReceiveSendsFromThread(const Thread* source); |
| 276 | |
| 277 | // If |source| is not null, pops the first "Send" message from |source| in |
| 278 | // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|. |
| 279 | // The caller must lock |crit_| before calling. |
| 280 | // Returns true if there is such a message. |
| 281 | bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg); |
| 282 | |
| 283 | void InvokeInternal(const Location& posted_from, MessageHandler* handler); |
| 284 | |
| 285 | std::list<_SendMessage> sendlist_; |
| 286 | std::string name_; |
| 287 | Event running_; // Signalled means running. |
| 288 | |
| 289 | #if defined(WEBRTC_POSIX) |
| 290 | pthread_t thread_; |
| 291 | #endif |
| 292 | |
| 293 | #if defined(WEBRTC_WIN) |
| 294 | HANDLE thread_; |
| 295 | DWORD thread_id_; |
| 296 | #endif |
| 297 | |
| 298 | bool owned_; |
| 299 | bool blocking_calls_allowed_; // By default set to |true|. |
| 300 | |
| 301 | friend class ThreadManager; |
| 302 | |
| 303 | RTC_DISALLOW_COPY_AND_ASSIGN(Thread); |
| 304 | }; |
| 305 | |
| 306 | // AutoThread automatically installs itself at construction |
| 307 | // uninstalls at destruction, if a Thread object is |
| 308 | // _not already_ associated with the current OS thread. |
| 309 | |
| 310 | class AutoThread : public Thread { |
| 311 | public: |
| 312 | AutoThread(); |
| 313 | ~AutoThread() override; |
| 314 | |
| 315 | private: |
| 316 | RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread); |
| 317 | }; |
| 318 | |
| 319 | // AutoSocketServerThread automatically installs itself at |
| 320 | // construction and uninstalls at destruction. If a Thread object is |
| 321 | // already associated with the current OS thread, it is temporarily |
| 322 | // disassociated and restored by the destructor. |
| 323 | |
| 324 | class AutoSocketServerThread : public Thread { |
| 325 | public: |
| 326 | explicit AutoSocketServerThread(SocketServer* ss); |
| 327 | ~AutoSocketServerThread() override; |
| 328 | |
| 329 | private: |
| 330 | rtc::Thread* old_thread_; |
| 331 | |
| 332 | RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread); |
| 333 | }; |
| 334 | |
| 335 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 336 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 337 | #endif // RTC_BASE_THREAD_H_ |