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