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> |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 15 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 16 | #include <list> |
| 17 | #include <memory> |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 18 | #include <queue> |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 19 | #include <string> |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 20 | #include <type_traits> |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 21 | #include <vector> |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 22 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 23 | #if defined(WEBRTC_POSIX) |
| 24 | #include <pthread.h> |
| 25 | #endif |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 26 | #include "api/function_view.h" |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 27 | #include "api/task_queue/queued_task.h" |
| 28 | #include "api/task_queue/task_queue_base.h" |
Steve Anton | 10542f2 | 2019-01-11 09:11:00 -0800 | [diff] [blame] | 29 | #include "rtc_base/constructor_magic.h" |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 30 | #include "rtc_base/critical_section.h" |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 31 | #include "rtc_base/location.h" |
Steve Anton | 10542f2 | 2019-01-11 09:11:00 -0800 | [diff] [blame] | 32 | #include "rtc_base/message_handler.h" |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 33 | #include "rtc_base/platform_thread_types.h" |
Steve Anton | 10542f2 | 2019-01-11 09:11:00 -0800 | [diff] [blame] | 34 | #include "rtc_base/socket_server.h" |
Mirko Bonadei | 35214fc | 2019-09-23 14:54:28 +0200 | [diff] [blame] | 35 | #include "rtc_base/system/rtc_export.h" |
Yves Gerey | 988cc08 | 2018-10-23 12:03:01 +0200 | [diff] [blame] | 36 | #include "rtc_base/thread_annotations.h" |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 37 | #include "rtc_base/thread_message.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 38 | |
| 39 | #if defined(WEBRTC_WIN) |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 40 | #include "rtc_base/win32.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 41 | #endif |
| 42 | |
| 43 | namespace rtc { |
| 44 | |
| 45 | class Thread; |
| 46 | |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 47 | namespace rtc_thread_internal { |
| 48 | |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 49 | class MessageLikeTask : public MessageData { |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 50 | public: |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 51 | virtual void Run() = 0; |
| 52 | }; |
| 53 | |
| 54 | template <class FunctorT> |
| 55 | class MessageWithFunctor final : public MessageLikeTask { |
| 56 | public: |
| 57 | explicit MessageWithFunctor(FunctorT&& functor) |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 58 | : functor_(std::forward<FunctorT>(functor)) {} |
| 59 | |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 60 | void Run() override { functor_(); } |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 61 | |
| 62 | private: |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 63 | ~MessageWithFunctor() override {} |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 64 | |
| 65 | typename std::remove_reference<FunctorT>::type functor_; |
| 66 | |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 67 | RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor); |
| 68 | }; |
| 69 | |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 70 | } // namespace rtc_thread_internal |
| 71 | |
Mirko Bonadei | 35214fc | 2019-09-23 14:54:28 +0200 | [diff] [blame] | 72 | class RTC_EXPORT ThreadManager { |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 73 | public: |
| 74 | static const int kForever = -1; |
| 75 | |
| 76 | // Singleton, constructor and destructor are private. |
| 77 | static ThreadManager* Instance(); |
| 78 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 79 | static void Add(Thread* message_queue); |
| 80 | static void Remove(Thread* message_queue); |
| 81 | static void Clear(MessageHandler* handler); |
| 82 | |
| 83 | // TODO(nisse): Delete alias, as soon as downstream code is updated. |
| 84 | static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); } |
| 85 | |
| 86 | // For testing purposes, for use with a simulated clock. |
| 87 | // Ensures that all message queues have processed delayed messages |
| 88 | // up until the current point in time. |
| 89 | static void ProcessAllMessageQueuesForTesting(); |
| 90 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 91 | Thread* CurrentThread(); |
| 92 | void SetCurrentThread(Thread* thread); |
| 93 | |
| 94 | // Returns a thread object with its thread_ ivar set |
| 95 | // to whatever the OS uses to represent the thread. |
| 96 | // If there already *is* a Thread object corresponding to this thread, |
| 97 | // this method will return that. Otherwise it creates a new Thread |
| 98 | // object whose wrapped() method will return true, and whose |
| 99 | // handle will, on Win32, be opened with only synchronization privileges - |
| 100 | // if you need more privilegs, rather than changing this method, please |
| 101 | // write additional code to adjust the privileges, or call a different |
| 102 | // factory method of your own devising, because this one gets used in |
| 103 | // unexpected contexts (like inside browser plugins) and it would be a |
| 104 | // shame to break it. It is also conceivable on Win32 that we won't even |
| 105 | // be able to get synchronization privileges, in which case the result |
| 106 | // will have a null handle. |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 107 | Thread* WrapCurrentThread(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 108 | void UnwrapCurrentThread(); |
| 109 | |
Niels Moller | 9d1840c | 2019-05-21 07:26:37 +0000 | [diff] [blame] | 110 | bool IsMainThread(); |
| 111 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 112 | private: |
| 113 | ThreadManager(); |
| 114 | ~ThreadManager(); |
| 115 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 116 | void AddInternal(Thread* message_queue); |
| 117 | void RemoveInternal(Thread* message_queue); |
| 118 | void ClearInternal(MessageHandler* handler); |
| 119 | void ProcessAllMessageQueuesInternal(); |
| 120 | |
| 121 | // This list contains all live Threads. |
| 122 | std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_); |
| 123 | |
| 124 | // Methods that don't modify the list of message queues may be called in a |
| 125 | // re-entrant fashion. "processing_" keeps track of the depth of re-entrant |
| 126 | // calls. |
| 127 | CriticalSection crit_; |
| 128 | size_t processing_ RTC_GUARDED_BY(crit_) = 0; |
| 129 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 130 | #if defined(WEBRTC_POSIX) |
| 131 | pthread_key_t key_; |
| 132 | #endif |
| 133 | |
| 134 | #if defined(WEBRTC_WIN) |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 135 | const DWORD key_; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 136 | #endif |
| 137 | |
Niels Moller | 9d1840c | 2019-05-21 07:26:37 +0000 | [diff] [blame] | 138 | // The thread to potentially autowrap. |
| 139 | const PlatformThreadRef main_thread_ref_; |
| 140 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 141 | RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager); |
| 142 | }; |
| 143 | |
| 144 | struct _SendMessage { |
| 145 | _SendMessage() {} |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 146 | Thread* thread; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 147 | Message msg; |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 148 | bool* ready; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 149 | }; |
| 150 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 151 | // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). |
| 152 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 153 | class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase { |
tommi | a8a3515 | 2017-07-13 05:47:25 -0700 | [diff] [blame] | 154 | public: |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 155 | static const int kForever = -1; |
| 156 | |
| 157 | // Create a new Thread and optionally assign it to the passed |
| 158 | // SocketServer. Subclasses that override Clear should pass false for |
| 159 | // init_queue and call DoInit() from their constructor to prevent races |
| 160 | // with the ThreadManager using the object while the vtable is still |
| 161 | // being created. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 162 | explicit Thread(SocketServer* ss); |
| 163 | explicit Thread(std::unique_ptr<SocketServer> ss); |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 164 | |
Taylor Brandstetter | 0867260 | 2018-03-02 15:20:33 -0800 | [diff] [blame] | 165 | // Constructors meant for subclasses; they should call DoInit themselves and |
| 166 | // pass false for |do_init|, so that DoInit is called only on the fully |
| 167 | // instantiated class, which avoids a vptr data race. |
| 168 | Thread(SocketServer* ss, bool do_init); |
| 169 | Thread(std::unique_ptr<SocketServer> ss, bool do_init); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 170 | |
| 171 | // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or |
| 172 | // guarantee Stop() is explicitly called before the subclass is destroyed). |
| 173 | // This is required to avoid a data race between the destructor modifying the |
| 174 | // vtable, and the Thread::PreRun calling the virtual method Run(). |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 175 | |
| 176 | // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL |
| 177 | // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race |
| 178 | // between the destructor modifying the vtable, and the ThreadManager |
| 179 | // calling Clear on the object from a different thread. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 180 | ~Thread() override; |
| 181 | |
| 182 | static std::unique_ptr<Thread> CreateWithSocketServer(); |
| 183 | static std::unique_ptr<Thread> Create(); |
| 184 | static Thread* Current(); |
| 185 | |
| 186 | // Used to catch performance regressions. Use this to disallow blocking calls |
| 187 | // (Invoke) for a given scope. If a synchronous call is made while this is in |
| 188 | // effect, an assert will be triggered. |
| 189 | // Note that this is a single threaded class. |
| 190 | class ScopedDisallowBlockingCalls { |
| 191 | public: |
| 192 | ScopedDisallowBlockingCalls(); |
Sebastian Jansson | 9debe5a | 2019-03-22 15:42:38 +0100 | [diff] [blame] | 193 | ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete; |
| 194 | ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) = |
| 195 | delete; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 196 | ~ScopedDisallowBlockingCalls(); |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 197 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 198 | private: |
| 199 | Thread* const thread_; |
| 200 | const bool previous_state_; |
| 201 | }; |
| 202 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 203 | SocketServer* socketserver(); |
| 204 | |
| 205 | // Note: The behavior of Thread has changed. When a thread is stopped, |
| 206 | // futher Posts and Sends will fail. However, any pending Sends and *ready* |
| 207 | // Posts (as opposed to unexpired delayed Posts) will be delivered before |
| 208 | // Get (or Peek) returns false. By guaranteeing delivery of those messages, |
| 209 | // we eliminate the race condition when an MessageHandler and Thread |
| 210 | // may be destroyed independently of each other. |
| 211 | virtual void Quit(); |
| 212 | virtual bool IsQuitting(); |
| 213 | virtual void Restart(); |
| 214 | // Not all message queues actually process messages (such as SignalThread). |
| 215 | // In those cases, it's important to know, before posting, that it won't be |
| 216 | // Processed. Normally, this would be true until IsQuitting() is true. |
| 217 | virtual bool IsProcessingMessagesForTesting(); |
| 218 | |
| 219 | // Get() will process I/O until: |
| 220 | // 1) A message is available (returns true) |
| 221 | // 2) cmsWait seconds have elapsed (returns false) |
| 222 | // 3) Stop() is called (returns false) |
| 223 | virtual bool Get(Message* pmsg, |
| 224 | int cmsWait = kForever, |
| 225 | bool process_io = true); |
| 226 | virtual bool Peek(Message* pmsg, int cmsWait = 0); |
| 227 | virtual void Post(const Location& posted_from, |
| 228 | MessageHandler* phandler, |
| 229 | uint32_t id = 0, |
| 230 | MessageData* pdata = nullptr, |
| 231 | bool time_sensitive = false); |
| 232 | virtual void PostDelayed(const Location& posted_from, |
| 233 | int cmsDelay, |
| 234 | MessageHandler* phandler, |
| 235 | uint32_t id = 0, |
| 236 | MessageData* pdata = nullptr); |
| 237 | virtual void PostAt(const Location& posted_from, |
| 238 | int64_t tstamp, |
| 239 | MessageHandler* phandler, |
| 240 | uint32_t id = 0, |
| 241 | MessageData* pdata = nullptr); |
| 242 | // TODO(honghaiz): Remove this when all the dependencies are removed. |
| 243 | virtual void PostAt(const Location& posted_from, |
| 244 | uint32_t tstamp, |
| 245 | MessageHandler* phandler, |
| 246 | uint32_t id = 0, |
| 247 | MessageData* pdata = nullptr); |
| 248 | virtual void Clear(MessageHandler* phandler, |
| 249 | uint32_t id = MQID_ANY, |
| 250 | MessageList* removed = nullptr); |
| 251 | virtual void Dispatch(Message* pmsg); |
| 252 | virtual void ReceiveSends(); |
| 253 | |
| 254 | // Amount of time until the next message can be retrieved |
| 255 | virtual int GetDelay(); |
| 256 | |
| 257 | bool empty() const { return size() == 0u; } |
| 258 | size_t size() const { |
| 259 | CritScope cs(&crit_); // msgq_.size() is not thread safe. |
| 260 | return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u); |
| 261 | } |
| 262 | |
| 263 | // Internally posts a message which causes the doomed object to be deleted |
| 264 | template <class T> |
| 265 | void Dispose(T* doomed) { |
| 266 | if (doomed) { |
| 267 | Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed)); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | // When this signal is sent out, any references to this queue should |
| 272 | // no longer be used. |
| 273 | sigslot::signal0<> SignalQueueDestroyed; |
| 274 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 275 | bool IsCurrent() const; |
| 276 | |
| 277 | // Sleeps the calling thread for the specified number of milliseconds, during |
| 278 | // which time no processing is performed. Returns false if sleeping was |
| 279 | // interrupted by a signal (POSIX only). |
| 280 | static bool SleepMs(int millis); |
| 281 | |
| 282 | // Sets the thread's name, for debugging. Must be called before Start(). |
| 283 | // If |obj| is non-null, its value is appended to |name|. |
| 284 | const std::string& name() const { return name_; } |
| 285 | bool SetName(const std::string& name, const void* obj); |
| 286 | |
| 287 | // Starts the execution of the thread. |
Niels Möller | d2e5013 | 2019-06-11 09:24:14 +0200 | [diff] [blame] | 288 | bool Start(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 289 | |
| 290 | // Tells the thread to stop and waits until it is joined. |
| 291 | // Never call Stop on the current thread. Instead use the inherited Quit |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 292 | // function which will exit the base Thread without terminating the |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 293 | // underlying OS thread. |
| 294 | virtual void Stop(); |
| 295 | |
| 296 | // By default, Thread::Run() calls ProcessMessages(kForever). To do other |
| 297 | // work, override Run(). To receive and dispatch messages, call |
| 298 | // ProcessMessages occasionally. |
| 299 | virtual void Run(); |
| 300 | |
| 301 | virtual void Send(const Location& posted_from, |
| 302 | MessageHandler* phandler, |
| 303 | uint32_t id = 0, |
| 304 | MessageData* pdata = nullptr); |
| 305 | |
| 306 | // Convenience method to invoke a functor on another thread. Caller must |
| 307 | // provide the |ReturnT| template argument, which cannot (easily) be deduced. |
| 308 | // Uses Send() internally, which blocks the current thread until execution |
| 309 | // is complete. |
| 310 | // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE, |
| 311 | // &MyFunctionReturningBool); |
| 312 | // NOTE: This function can only be called when synchronous calls are allowed. |
| 313 | // See ScopedDisallowBlockingCalls for details. |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 314 | // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can |
| 315 | // be achieved with PostTask() and callbacks instead. |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 316 | template < |
| 317 | class ReturnT, |
| 318 | typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type> |
| 319 | ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) { |
| 320 | ReturnT result; |
| 321 | InvokeInternal(posted_from, [functor, &result] { result = functor(); }); |
| 322 | return result; |
| 323 | } |
| 324 | |
| 325 | template < |
| 326 | class ReturnT, |
| 327 | typename = typename std::enable_if<std::is_void<ReturnT>::value>::type> |
| 328 | void Invoke(const Location& posted_from, FunctionView<void()> functor) { |
| 329 | InvokeInternal(posted_from, functor); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 330 | } |
| 331 | |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 332 | // Posts a task to invoke the functor on |this| thread asynchronously, i.e. |
| 333 | // without blocking the thread that invoked PostTask(). Ownership of |functor| |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 334 | // is passed and (usually, see below) destroyed on |this| thread after it is |
| 335 | // invoked. |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 336 | // Requirements of FunctorT: |
| 337 | // - FunctorT is movable. |
| 338 | // - FunctorT implements "T operator()()" or "T operator()() const" for some T |
| 339 | // (if T is not void, the return value is discarded on |this| thread). |
| 340 | // - FunctorT has a public destructor that can be invoked from |this| thread |
| 341 | // after operation() has been invoked. |
| 342 | // - The functor must not cause the thread to quit before PostTask() is done. |
| 343 | // |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 344 | // Destruction of the functor/task mimics what TaskQueue::PostTask does: If |
| 345 | // the task is run, it will be destroyed on |this| thread. However, if there |
| 346 | // are pending tasks by the time the Thread is destroyed, or a task is posted |
| 347 | // to a thread that is quitting, the task is destroyed immediately, on the |
| 348 | // calling thread. Destroying the Thread only blocks for any currently running |
| 349 | // task to complete. Note that TQ abstraction is even vaguer on how |
| 350 | // destruction happens in these cases, allowing destruction to happen |
| 351 | // asynchronously at a later time and on some arbitrary thread. So to ease |
| 352 | // migration, don't depend on Thread::PostTask destroying un-run tasks |
| 353 | // immediately. |
| 354 | // |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 355 | // Example - Calling a class method: |
| 356 | // class Foo { |
| 357 | // public: |
| 358 | // void DoTheThing(); |
| 359 | // }; |
| 360 | // Foo foo; |
| 361 | // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo)); |
| 362 | // |
| 363 | // Example - Calling a lambda function: |
| 364 | // thread->PostTask(RTC_FROM_HERE, |
| 365 | // [&x, &y] { x.TrackComputations(y.Compute()); }); |
| 366 | template <class FunctorT> |
| 367 | void PostTask(const Location& posted_from, FunctorT&& functor) { |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 368 | Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0, |
Niels Möller | f13a096 | 2019-05-17 10:15:06 +0200 | [diff] [blame] | 369 | new rtc_thread_internal::MessageWithFunctor<FunctorT>( |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 370 | std::forward<FunctorT>(functor))); |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 371 | } |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 372 | template <class FunctorT> |
| 373 | void PostDelayedTask(const Location& posted_from, |
| 374 | FunctorT&& functor, |
| 375 | uint32_t milliseconds) { |
| 376 | PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(), |
| 377 | /*id=*/0, |
| 378 | new rtc_thread_internal::MessageWithFunctor<FunctorT>( |
| 379 | std::forward<FunctorT>(functor))); |
| 380 | } |
Henrik Boström | ba4dcc3 | 2019-02-28 09:34:06 +0100 | [diff] [blame] | 381 | |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 382 | // From TaskQueueBase |
| 383 | void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override; |
| 384 | void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task, |
| 385 | uint32_t milliseconds) override; |
| 386 | void Delete() override; |
| 387 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 388 | // ProcessMessages will process I/O and dispatch messages until: |
| 389 | // 1) cms milliseconds have elapsed (returns true) |
| 390 | // 2) Stop() is called (returns false) |
| 391 | bool ProcessMessages(int cms); |
| 392 | |
| 393 | // Returns true if this is a thread that we created using the standard |
| 394 | // constructor, false if it was created by a call to |
| 395 | // ThreadManager::WrapCurrentThread(). The main thread of an application |
| 396 | // is generally not owned, since the OS representation of the thread |
| 397 | // obviously exists before we can get to it. |
| 398 | // You cannot call Start on non-owned threads. |
| 399 | bool IsOwned(); |
| 400 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 401 | // Expose private method IsRunning() for tests. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 402 | // |
| 403 | // DANGER: this is a terrible public API. Most callers that might want to |
| 404 | // call this likely do not have enough control/knowledge of the Thread in |
| 405 | // question to guarantee that the returned value remains true for the duration |
| 406 | // of whatever code is conditionally executing because of the return value! |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 407 | bool RunningForTest() { return IsRunning(); } |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 408 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 409 | // These functions are public to avoid injecting test hooks. Don't call them |
| 410 | // outside of tests. |
| 411 | // This method should be called when thread is created using non standard |
| 412 | // method, like derived implementation of rtc::Thread and it can not be |
| 413 | // started by calling Start(). This will set started flag to true and |
| 414 | // owned to false. This must be called from the current thread. |
| 415 | bool WrapCurrent(); |
| 416 | void UnwrapCurrent(); |
| 417 | |
Karl Wiberg | 3256225 | 2019-02-21 13:38:30 +0100 | [diff] [blame] | 418 | // Sets the per-thread allow-blocking-calls flag to false; this is |
| 419 | // irrevocable. Must be called on this thread. |
| 420 | void DisallowBlockingCalls() { SetAllowBlockingCalls(false); } |
| 421 | |
| 422 | #ifdef WEBRTC_ANDROID |
| 423 | // Sets the per-thread allow-blocking-calls flag to true, sidestepping the |
| 424 | // invariants upheld by DisallowBlockingCalls() and |
| 425 | // ScopedDisallowBlockingCalls. Must be called on this thread. |
| 426 | void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); } |
| 427 | #endif |
| 428 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 429 | protected: |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 430 | class PriorityQueue : public std::priority_queue<DelayedMessage> { |
| 431 | public: |
| 432 | container_type& container() { return c; } |
| 433 | void reheap() { make_heap(c.begin(), c.end(), comp); } |
| 434 | }; |
| 435 | |
| 436 | void DoDelayPost(const Location& posted_from, |
| 437 | int64_t cmsDelay, |
| 438 | int64_t tstamp, |
| 439 | MessageHandler* phandler, |
| 440 | uint32_t id, |
| 441 | MessageData* pdata); |
| 442 | |
| 443 | // Perform initialization, subclasses must call this from their constructor |
| 444 | // if false was passed as init_queue to the Thread constructor. |
| 445 | void DoInit(); |
| 446 | |
| 447 | // Does not take any lock. Must be called either while holding crit_, or by |
| 448 | // the destructor (by definition, the latter has exclusive access). |
| 449 | void ClearInternal(MessageHandler* phandler, |
| 450 | uint32_t id, |
| 451 | MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_); |
| 452 | |
| 453 | // Perform cleanup; subclasses must call this from the destructor, |
| 454 | // and are not expected to actually hold the lock. |
| 455 | void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_); |
| 456 | |
| 457 | void WakeUpSocketServer(); |
| 458 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 459 | // Same as WrapCurrent except that it never fails as it does not try to |
| 460 | // acquire the synchronization access of the thread. The caller should never |
| 461 | // call Stop() or Join() on this thread. |
| 462 | void SafeWrapCurrent(); |
| 463 | |
| 464 | // Blocks the calling thread until this thread has terminated. |
| 465 | void Join(); |
| 466 | |
| 467 | static void AssertBlockingIsAllowedOnCurrentThread(); |
| 468 | |
| 469 | friend class ScopedDisallowBlockingCalls; |
| 470 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 471 | CriticalSection* CritForTest() { return &crit_; } |
| 472 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 473 | private: |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 474 | class QueuedTaskHandler final : public MessageHandler { |
| 475 | public: |
| 476 | void OnMessage(Message* msg) override; |
| 477 | }; |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 478 | |
Karl Wiberg | 3256225 | 2019-02-21 13:38:30 +0100 | [diff] [blame] | 479 | // Sets the per-thread allow-blocking-calls flag and returns the previous |
| 480 | // value. Must be called on this thread. |
| 481 | bool SetAllowBlockingCalls(bool allow); |
| 482 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 483 | #if defined(WEBRTC_WIN) |
| 484 | static DWORD WINAPI PreRun(LPVOID context); |
| 485 | #else |
Yves Gerey | 665174f | 2018-06-19 15:03:05 +0200 | [diff] [blame] | 486 | static void* PreRun(void* pv); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 487 | #endif |
| 488 | |
| 489 | // ThreadManager calls this instead WrapCurrent() because |
| 490 | // ThreadManager::Instance() cannot be used while ThreadManager is |
| 491 | // being created. |
| 492 | // The method tries to get synchronization rights of the thread on Windows if |
| 493 | // |need_synchronize_access| is true. |
| 494 | bool WrapCurrentWithThreadManager(ThreadManager* thread_manager, |
| 495 | bool need_synchronize_access); |
| 496 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 497 | // Return true if the thread is currently running. |
| 498 | bool IsRunning(); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 499 | |
| 500 | // Processes received "Send" requests. If |source| is not null, only requests |
| 501 | // from |source| are processed, otherwise, all requests are processed. |
| 502 | void ReceiveSendsFromThread(const Thread* source); |
| 503 | |
| 504 | // If |source| is not null, pops the first "Send" message from |source| in |
| 505 | // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|. |
| 506 | // The caller must lock |crit_| before calling. |
| 507 | // Returns true if there is such a message. |
| 508 | bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg); |
| 509 | |
Danil Chapovalov | 8931345 | 2019-11-29 12:56:43 +0100 | [diff] [blame] | 510 | void InvokeInternal(const Location& posted_from, |
| 511 | rtc::FunctionView<void()> functor); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 512 | |
Steve Anton | bcc1a76 | 2019-12-11 11:21:53 -0800 | [diff] [blame] | 513 | // Returns a static-lifetime MessageHandler which runs message with |
| 514 | // MessageLikeTask payload data. |
| 515 | static MessageHandler* GetPostTaskMessageHandler(); |
| 516 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 517 | bool fPeekKeep_; |
| 518 | Message msgPeek_; |
| 519 | MessageList msgq_ RTC_GUARDED_BY(crit_); |
| 520 | PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_); |
| 521 | uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_); |
| 522 | CriticalSection crit_; |
| 523 | bool fInitialized_; |
| 524 | bool fDestroyed_; |
| 525 | |
| 526 | volatile int stop_; |
| 527 | |
| 528 | // The SocketServer might not be owned by Thread. |
| 529 | SocketServer* const ss_; |
| 530 | // Used if SocketServer ownership lies with |this|. |
| 531 | std::unique_ptr<SocketServer> own_ss_; |
| 532 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 533 | std::list<_SendMessage> sendlist_; |
| 534 | std::string name_; |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 535 | |
Jonas Olsson | a4d8737 | 2019-07-05 19:08:33 +0200 | [diff] [blame] | 536 | // TODO(tommi): Add thread checks for proper use of control methods. |
| 537 | // Ideally we should be able to just use PlatformThread. |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 538 | |
| 539 | #if defined(WEBRTC_POSIX) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 540 | pthread_t thread_ = 0; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 541 | #endif |
| 542 | |
| 543 | #if defined(WEBRTC_WIN) |
Tommi | 6cea2b0 | 2017-12-04 18:51:16 +0100 | [diff] [blame] | 544 | HANDLE thread_ = nullptr; |
| 545 | DWORD thread_id_ = 0; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 546 | #endif |
| 547 | |
Tommi | 5149242 | 2017-12-04 15:18:23 +0100 | [diff] [blame] | 548 | // Indicates whether or not ownership of the worker thread lies with |
| 549 | // this instance or not. (i.e. owned_ == !wrapped). |
| 550 | // Must only be modified when the worker thread is not running. |
| 551 | bool owned_ = true; |
| 552 | |
| 553 | // Only touched from the worker thread itself. |
| 554 | bool blocking_calls_allowed_ = true; |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 555 | |
Danil Chapovalov | 912b3b8 | 2019-11-22 15:52:40 +0100 | [diff] [blame] | 556 | // Runs webrtc::QueuedTask posted to the Thread. |
| 557 | QueuedTaskHandler queued_task_handler_; |
| 558 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 559 | friend class ThreadManager; |
| 560 | |
| 561 | RTC_DISALLOW_COPY_AND_ASSIGN(Thread); |
| 562 | }; |
| 563 | |
| 564 | // AutoThread automatically installs itself at construction |
| 565 | // uninstalls at destruction, if a Thread object is |
| 566 | // _not already_ associated with the current OS thread. |
| 567 | |
| 568 | class AutoThread : public Thread { |
| 569 | public: |
| 570 | AutoThread(); |
| 571 | ~AutoThread() override; |
| 572 | |
| 573 | private: |
| 574 | RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread); |
| 575 | }; |
| 576 | |
| 577 | // AutoSocketServerThread automatically installs itself at |
| 578 | // construction and uninstalls at destruction. If a Thread object is |
| 579 | // already associated with the current OS thread, it is temporarily |
| 580 | // disassociated and restored by the destructor. |
| 581 | |
| 582 | class AutoSocketServerThread : public Thread { |
| 583 | public: |
| 584 | explicit AutoSocketServerThread(SocketServer* ss); |
| 585 | ~AutoSocketServerThread() override; |
| 586 | |
| 587 | private: |
| 588 | rtc::Thread* old_thread_; |
| 589 | |
| 590 | RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread); |
| 591 | }; |
| 592 | |
Sebastian Jansson | 6ea2c6a | 2020-01-13 14:07:22 +0100 | [diff] [blame] | 593 | // TODO(srte): Remove these when all dependencies has been updated. |
| 594 | using MessageQueue = Thread; |
| 595 | using MessageQueueManager = ThreadManager; |
| 596 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 597 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 598 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 599 | #endif // RTC_BASE_THREAD_H_ |