blob: d950b06c41e00677c0295e74c37a7e67c146ef85 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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 Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_THREAD_H_
12#define RTC_BASE_THREAD_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <list>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010017#include <map>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#include <memory>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010019#include <queue>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010020#include <set>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020021#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020022#include <type_traits>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010023#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025#if defined(WEBRTC_POSIX)
26#include <pthread.h>
27#endif
Danil Chapovalov89313452019-11-29 12:56:43 +010028#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010029#include "api/task_queue/queued_task.h"
30#include "api/task_queue/task_queue_base.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/constructor_magic.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020032#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020037#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020038#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010039#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020040
41#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043#endif
44
Tommife041642021-04-07 10:08:28 +020045#if RTC_DCHECK_IS_ON
46// Counts how many blocking Thread::Invoke or Thread::Send calls are made from
47// within a scope and logs the number of blocking calls at the end of the scope.
48#define RTC_LOG_THREAD_BLOCK_COUNT() \
49 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
50 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
51 auto total = actual_block + could_block; \
52 if (total) { \
53 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
54 << " (actual=" << actual_block \
55 << ", could=" << could_block << ")"; \
56 } \
57 })
58
59// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
60// less than or equal to a specific value. Use to avoid regressing in the
61// number of blocking thread calls.
62// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
63// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020064#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
65 do { \
66 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
67 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
68 } while (0)
Tommife041642021-04-07 10:08:28 +020069#else
70#define RTC_LOG_THREAD_BLOCK_COUNT()
71#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
72#endif
73
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020074namespace rtc {
75
76class Thread;
77
Henrik Boströmba4dcc32019-02-28 09:34:06 +010078namespace rtc_thread_internal {
79
Niels Möllerf13a0962019-05-17 10:15:06 +020080class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010081 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020082 virtual void Run() = 0;
83};
84
85template <class FunctorT>
86class MessageWithFunctor final : public MessageLikeTask {
87 public:
88 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010089 : functor_(std::forward<FunctorT>(functor)) {}
90
Niels Möllerf13a0962019-05-17 10:15:06 +020091 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010092
93 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020094 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010095
96 typename std::remove_reference<FunctorT>::type functor_;
97
Niels Möllerf13a0962019-05-17 10:15:06 +020098 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
99};
100
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100101} // namespace rtc_thread_internal
102
Mirko Bonadei35214fc2019-09-23 14:54:28 +0200103class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200104 public:
105 static const int kForever = -1;
106
107 // Singleton, constructor and destructor are private.
108 static ThreadManager* Instance();
109
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100110 static void Add(Thread* message_queue);
111 static void Remove(Thread* message_queue);
112 static void Clear(MessageHandler* handler);
113
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100114 // For testing purposes, for use with a simulated clock.
115 // Ensures that all message queues have processed delayed messages
116 // up until the current point in time.
117 static void ProcessAllMessageQueuesForTesting();
118
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119 Thread* CurrentThread();
120 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +0100121 // Allows changing the current thread, this is intended for tests where we
122 // want to simulate multiple threads running on a single physical thread.
123 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124
125 // Returns a thread object with its thread_ ivar set
126 // to whatever the OS uses to represent the thread.
127 // If there already *is* a Thread object corresponding to this thread,
128 // this method will return that. Otherwise it creates a new Thread
129 // object whose wrapped() method will return true, and whose
130 // handle will, on Win32, be opened with only synchronization privileges -
131 // if you need more privilegs, rather than changing this method, please
132 // write additional code to adjust the privileges, or call a different
133 // factory method of your own devising, because this one gets used in
134 // unexpected contexts (like inside browser plugins) and it would be a
135 // shame to break it. It is also conceivable on Win32 that we won't even
136 // be able to get synchronization privileges, in which case the result
137 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200138 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200139 void UnwrapCurrentThread();
140
Niels Moller9d1840c2019-05-21 07:26:37 +0000141 bool IsMainThread();
142
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100143#if RTC_DCHECK_IS_ON
Artem Titov96e3b992021-07-26 16:03:14 +0200144 // Registers that a Send operation is to be performed between `source` and
145 // `target`, while checking that this does not cause a send cycle that could
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100146 // potentially cause a deadlock.
147 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
148#endif
149
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200150 private:
151 ThreadManager();
152 ~ThreadManager();
153
Sebastian Jansson178a6852020-01-14 11:12:26 +0100154 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100155 void AddInternal(Thread* message_queue);
156 void RemoveInternal(Thread* message_queue);
157 void ClearInternal(MessageHandler* handler);
158 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100159#if RTC_DCHECK_IS_ON
160 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
161#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100162
163 // This list contains all live Threads.
164 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
165
166 // Methods that don't modify the list of message queues may be called in a
167 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
168 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200169 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100170 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100171#if RTC_DCHECK_IS_ON
172 // Represents all thread seand actions by storing all send targets per thread.
173 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
174 // since we will trigger a CHECK failure if a cycle is introduced.
175 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
176#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100177
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200178#if defined(WEBRTC_POSIX)
179 pthread_key_t key_;
180#endif
181
182#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100183 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200184#endif
185
Niels Moller9d1840c2019-05-21 07:26:37 +0000186 // The thread to potentially autowrap.
187 const PlatformThreadRef main_thread_ref_;
188
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200189 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
190};
191
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200192// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
193
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100194class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700195 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100196 static const int kForever = -1;
197
198 // Create a new Thread and optionally assign it to the passed
199 // SocketServer. Subclasses that override Clear should pass false for
200 // init_queue and call DoInit() from their constructor to prevent races
201 // with the ThreadManager using the object while the vtable is still
202 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200203 explicit Thread(SocketServer* ss);
204 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100205
Taylor Brandstetter08672602018-03-02 15:20:33 -0800206 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200207 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800208 // instantiated class, which avoids a vptr data race.
209 Thread(SocketServer* ss, bool do_init);
210 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200211
212 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
213 // guarantee Stop() is explicitly called before the subclass is destroyed).
214 // This is required to avoid a data race between the destructor modifying the
215 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100216
217 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
218 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
219 // between the destructor modifying the vtable, and the ThreadManager
220 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200221 ~Thread() override;
222
223 static std::unique_ptr<Thread> CreateWithSocketServer();
224 static std::unique_ptr<Thread> Create();
225 static Thread* Current();
226
227 // Used to catch performance regressions. Use this to disallow blocking calls
228 // (Invoke) for a given scope. If a synchronous call is made while this is in
229 // effect, an assert will be triggered.
230 // Note that this is a single threaded class.
231 class ScopedDisallowBlockingCalls {
232 public:
233 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100234 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
235 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
236 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200237 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200238
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200239 private:
240 Thread* const thread_;
241 const bool previous_state_;
242 };
243
Tommife041642021-04-07 10:08:28 +0200244#if RTC_DCHECK_IS_ON
245 class ScopedCountBlockingCalls {
246 public:
247 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
248 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
249 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
250 delete;
251 ~ScopedCountBlockingCalls();
252
253 uint32_t GetBlockingCallCount() const;
254 uint32_t GetCouldBeBlockingCallCount() const;
255 uint32_t GetTotalBlockedCallCount() const;
256
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200257 void set_minimum_call_count_for_callback(uint32_t minimum) {
258 min_blocking_calls_for_callback_ = minimum;
259 }
260
Tommife041642021-04-07 10:08:28 +0200261 private:
262 Thread* const thread_;
263 const uint32_t base_blocking_call_count_;
264 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200265 // The minimum number of blocking calls required in order to issue the
266 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
267 // tame log spam.
268 // By default we always issue the callback, regardless of callback count.
269 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200270 std::function<void(uint32_t, uint32_t)> result_callback_;
271 };
272
273 uint32_t GetBlockingCallCount() const;
274 uint32_t GetCouldBeBlockingCallCount() const;
275#endif
276
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100277 SocketServer* socketserver();
278
279 // Note: The behavior of Thread has changed. When a thread is stopped,
280 // futher Posts and Sends will fail. However, any pending Sends and *ready*
281 // Posts (as opposed to unexpired delayed Posts) will be delivered before
282 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
283 // we eliminate the race condition when an MessageHandler and Thread
284 // may be destroyed independently of each other.
285 virtual void Quit();
286 virtual bool IsQuitting();
287 virtual void Restart();
288 // Not all message queues actually process messages (such as SignalThread).
289 // In those cases, it's important to know, before posting, that it won't be
290 // Processed. Normally, this would be true until IsQuitting() is true.
291 virtual bool IsProcessingMessagesForTesting();
292
293 // Get() will process I/O until:
294 // 1) A message is available (returns true)
295 // 2) cmsWait seconds have elapsed (returns false)
296 // 3) Stop() is called (returns false)
297 virtual bool Get(Message* pmsg,
298 int cmsWait = kForever,
299 bool process_io = true);
300 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Artem Titov96e3b992021-07-26 16:03:14 +0200301 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100302 virtual void Post(const Location& posted_from,
303 MessageHandler* phandler,
304 uint32_t id = 0,
305 MessageData* pdata = nullptr,
306 bool time_sensitive = false);
307 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100308 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100309 MessageHandler* phandler,
310 uint32_t id = 0,
311 MessageData* pdata = nullptr);
312 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100313 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100314 MessageHandler* phandler,
315 uint32_t id = 0,
316 MessageData* pdata = nullptr);
317 virtual void Clear(MessageHandler* phandler,
318 uint32_t id = MQID_ANY,
319 MessageList* removed = nullptr);
320 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100321
322 // Amount of time until the next message can be retrieved
323 virtual int GetDelay();
324
325 bool empty() const { return size() == 0u; }
326 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100327 CritScope cs(&crit_);
328 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100329 }
330
331 // Internally posts a message which causes the doomed object to be deleted
332 template <class T>
333 void Dispose(T* doomed) {
334 if (doomed) {
335 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
336 }
337 }
338
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200339 bool IsCurrent() const;
340
341 // Sleeps the calling thread for the specified number of milliseconds, during
342 // which time no processing is performed. Returns false if sleeping was
343 // interrupted by a signal (POSIX only).
344 static bool SleepMs(int millis);
345
346 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200347 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200348 const std::string& name() const { return name_; }
349 bool SetName(const std::string& name, const void* obj);
350
Harald Alvestrandba694422021-01-27 21:52:14 +0000351 // Sets the expected processing time in ms. The thread will write
352 // log messages when Invoke() takes more time than this.
353 // Default is 50 ms.
354 void SetDispatchWarningMs(int deadline);
355
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200356 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200357 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200358
359 // Tells the thread to stop and waits until it is joined.
360 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100361 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200362 // underlying OS thread.
363 virtual void Stop();
364
365 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
366 // work, override Run(). To receive and dispatch messages, call
367 // ProcessMessages occasionally.
368 virtual void Run();
369
370 virtual void Send(const Location& posted_from,
371 MessageHandler* phandler,
372 uint32_t id = 0,
373 MessageData* pdata = nullptr);
374
375 // Convenience method to invoke a functor on another thread. Caller must
Artem Titov96e3b992021-07-26 16:03:14 +0200376 // provide the `ReturnT` template argument, which cannot (easily) be deduced.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200377 // Uses Send() internally, which blocks the current thread until execution
378 // is complete.
379 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
380 // &MyFunctionReturningBool);
381 // NOTE: This function can only be called when synchronous calls are allowed.
382 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100383 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
384 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100385 template <
386 class ReturnT,
387 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
388 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
389 ReturnT result;
390 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
391 return result;
392 }
393
394 template <
395 class ReturnT,
396 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
397 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
398 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200399 }
400
Artem Titov96e3b992021-07-26 16:03:14 +0200401 // Allows invoke to specified `thread`. Thread never will be dereferenced and
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200402 // will be used only for reference-based comparison, so instance can be safely
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200403 // deleted. If NDEBUG is defined and RTC_DCHECK_ALWAYS_ON is undefined do
404 // nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200405 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200406
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200407 // If NDEBUG is defined and RTC_DCHECK_ALWAYS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200408 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200409 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200410 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
411 // returns false.
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200412 // If NDEBUG is defined and RTC_DCHECK_ALWAYS_ON is undefined always returns
413 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200414 bool IsInvokeToThreadAllowed(rtc::Thread* target);
415
Artem Titov96e3b992021-07-26 16:03:14 +0200416 // Posts a task to invoke the functor on `this` thread asynchronously, i.e.
417 // without blocking the thread that invoked PostTask(). Ownership of `functor`
418 // is passed and (usually, see below) destroyed on `this` thread after it is
Niels Möllerf13a0962019-05-17 10:15:06 +0200419 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100420 // Requirements of FunctorT:
421 // - FunctorT is movable.
422 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
Artem Titov96e3b992021-07-26 16:03:14 +0200423 // (if T is not void, the return value is discarded on `this` thread).
424 // - FunctorT has a public destructor that can be invoked from `this` thread
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100425 // after operation() has been invoked.
426 // - The functor must not cause the thread to quit before PostTask() is done.
427 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200428 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
Artem Titov96e3b992021-07-26 16:03:14 +0200429 // the task is run, it will be destroyed on `this` thread. However, if there
Niels Möllerf13a0962019-05-17 10:15:06 +0200430 // are pending tasks by the time the Thread is destroyed, or a task is posted
431 // to a thread that is quitting, the task is destroyed immediately, on the
432 // calling thread. Destroying the Thread only blocks for any currently running
433 // task to complete. Note that TQ abstraction is even vaguer on how
434 // destruction happens in these cases, allowing destruction to happen
435 // asynchronously at a later time and on some arbitrary thread. So to ease
436 // migration, don't depend on Thread::PostTask destroying un-run tasks
437 // immediately.
438 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100439 // Example - Calling a class method:
440 // class Foo {
441 // public:
442 // void DoTheThing();
443 // };
444 // Foo foo;
445 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
446 //
447 // Example - Calling a lambda function:
448 // thread->PostTask(RTC_FROM_HERE,
449 // [&x, &y] { x.TrackComputations(y.Compute()); });
450 template <class FunctorT>
451 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800452 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200453 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100454 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100455 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800456 template <class FunctorT>
457 void PostDelayedTask(const Location& posted_from,
458 FunctorT&& functor,
459 uint32_t milliseconds) {
460 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
461 /*id=*/0,
462 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
463 std::forward<FunctorT>(functor)));
464 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100465
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100466 // From TaskQueueBase
467 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
468 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
469 uint32_t milliseconds) override;
470 void Delete() override;
471
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200472 // ProcessMessages will process I/O and dispatch messages until:
473 // 1) cms milliseconds have elapsed (returns true)
474 // 2) Stop() is called (returns false)
475 bool ProcessMessages(int cms);
476
477 // Returns true if this is a thread that we created using the standard
478 // constructor, false if it was created by a call to
479 // ThreadManager::WrapCurrentThread(). The main thread of an application
480 // is generally not owned, since the OS representation of the thread
481 // obviously exists before we can get to it.
482 // You cannot call Start on non-owned threads.
483 bool IsOwned();
484
Tommi51492422017-12-04 15:18:23 +0100485 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200486 //
487 // DANGER: this is a terrible public API. Most callers that might want to
488 // call this likely do not have enough control/knowledge of the Thread in
489 // question to guarantee that the returned value remains true for the duration
490 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100491 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200492
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200493 // These functions are public to avoid injecting test hooks. Don't call them
494 // outside of tests.
495 // This method should be called when thread is created using non standard
496 // method, like derived implementation of rtc::Thread and it can not be
497 // started by calling Start(). This will set started flag to true and
498 // owned to false. This must be called from the current thread.
499 bool WrapCurrent();
500 void UnwrapCurrent();
501
Karl Wiberg32562252019-02-21 13:38:30 +0100502 // Sets the per-thread allow-blocking-calls flag to false; this is
503 // irrevocable. Must be called on this thread.
504 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
505
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100507 class CurrentThreadSetter : CurrentTaskQueueSetter {
508 public:
509 explicit CurrentThreadSetter(Thread* thread)
510 : CurrentTaskQueueSetter(thread),
511 manager_(rtc::ThreadManager::Instance()),
512 previous_(manager_->CurrentThread()) {
513 manager_->ChangeCurrentThreadForTest(thread);
514 }
515 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
516
517 private:
518 rtc::ThreadManager* const manager_;
519 rtc::Thread* const previous_;
520 };
521
Sebastian Jansson61380c02020-01-17 14:46:08 +0100522 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
523 // with the same trigger time are processed in num_ (FIFO) order.
524 class DelayedMessage {
525 public:
526 DelayedMessage(int64_t delay,
527 int64_t run_time_ms,
528 uint32_t num,
529 const Message& msg)
530 : delay_ms_(delay),
531 run_time_ms_(run_time_ms),
532 message_number_(num),
533 msg_(msg) {}
534
535 bool operator<(const DelayedMessage& dmsg) const {
536 return (dmsg.run_time_ms_ < run_time_ms_) ||
537 ((dmsg.run_time_ms_ == run_time_ms_) &&
538 (dmsg.message_number_ < message_number_));
539 }
540
541 int64_t delay_ms_; // for debugging
542 int64_t run_time_ms_;
543 // Monotonicaly incrementing number used for ordering of messages
544 // targeted to execute at the same time.
545 uint32_t message_number_;
546 Message msg_;
547 };
548
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100549 class PriorityQueue : public std::priority_queue<DelayedMessage> {
550 public:
551 container_type& container() { return c; }
552 void reheap() { make_heap(c.begin(), c.end(), comp); }
553 };
554
555 void DoDelayPost(const Location& posted_from,
556 int64_t cmsDelay,
557 int64_t tstamp,
558 MessageHandler* phandler,
559 uint32_t id,
560 MessageData* pdata);
561
562 // Perform initialization, subclasses must call this from their constructor
563 // if false was passed as init_queue to the Thread constructor.
564 void DoInit();
565
566 // Does not take any lock. Must be called either while holding crit_, or by
567 // the destructor (by definition, the latter has exclusive access).
568 void ClearInternal(MessageHandler* phandler,
569 uint32_t id,
570 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
571
572 // Perform cleanup; subclasses must call this from the destructor,
573 // and are not expected to actually hold the lock.
574 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
575
576 void WakeUpSocketServer();
577
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200578 // Same as WrapCurrent except that it never fails as it does not try to
579 // acquire the synchronization access of the thread. The caller should never
580 // call Stop() or Join() on this thread.
581 void SafeWrapCurrent();
582
583 // Blocks the calling thread until this thread has terminated.
584 void Join();
585
586 static void AssertBlockingIsAllowedOnCurrentThread();
587
588 friend class ScopedDisallowBlockingCalls;
589
Markus Handell3cb525b2020-07-16 16:16:09 +0200590 RecursiveCriticalSection* CritForTest() { return &crit_; }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100591
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200592 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000593 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
594
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100595 class QueuedTaskHandler final : public MessageHandler {
596 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200597 QueuedTaskHandler() {}
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100598 void OnMessage(Message* msg) override;
599 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800600
Karl Wiberg32562252019-02-21 13:38:30 +0100601 // Sets the per-thread allow-blocking-calls flag and returns the previous
602 // value. Must be called on this thread.
603 bool SetAllowBlockingCalls(bool allow);
604
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200605#if defined(WEBRTC_WIN)
606 static DWORD WINAPI PreRun(LPVOID context);
607#else
Yves Gerey665174f2018-06-19 15:03:05 +0200608 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200609#endif
610
611 // ThreadManager calls this instead WrapCurrent() because
612 // ThreadManager::Instance() cannot be used while ThreadManager is
613 // being created.
614 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200615 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200616 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
617 bool need_synchronize_access);
618
Tommi51492422017-12-04 15:18:23 +0100619 // Return true if the thread is currently running.
620 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200621
Danil Chapovalov89313452019-11-29 12:56:43 +0100622 void InvokeInternal(const Location& posted_from,
623 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200624
Tommi6866dc72020-05-15 10:11:56 +0200625 // Called by the ThreadManager when being set as the current thread.
626 void EnsureIsCurrentTaskQueue();
627
628 // Called by the ThreadManager when being unset as the current thread.
629 void ClearCurrentTaskQueue();
630
Steve Antonbcc1a762019-12-11 11:21:53 -0800631 // Returns a static-lifetime MessageHandler which runs message with
632 // MessageLikeTask payload data.
633 static MessageHandler* GetPostTaskMessageHandler();
634
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100635 bool fPeekKeep_;
636 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100637 MessageList messages_ RTC_GUARDED_BY(crit_);
638 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
639 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200640#if RTC_DCHECK_IS_ON
641 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
642 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200643 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
644 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
645#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200646 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100647 bool fInitialized_;
648 bool fDestroyed_;
649
650 volatile int stop_;
651
652 // The SocketServer might not be owned by Thread.
653 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200654 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100655 std::unique_ptr<SocketServer> own_ss_;
656
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200657 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100658
Jonas Olssona4d87372019-07-05 19:08:33 +0200659 // TODO(tommi): Add thread checks for proper use of control methods.
660 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200661
662#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100663 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200664#endif
665
666#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100667 HANDLE thread_ = nullptr;
668 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200669#endif
670
Tommi51492422017-12-04 15:18:23 +0100671 // Indicates whether or not ownership of the worker thread lies with
672 // this instance or not. (i.e. owned_ == !wrapped).
673 // Must only be modified when the worker thread is not running.
674 bool owned_ = true;
675
676 // Only touched from the worker thread itself.
677 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200678
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100679 // Runs webrtc::QueuedTask posted to the Thread.
680 QueuedTaskHandler queued_task_handler_;
Tommi6866dc72020-05-15 10:11:56 +0200681 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
682 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100683
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200684 friend class ThreadManager;
685
Harald Alvestrandba694422021-01-27 21:52:14 +0000686 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
687
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200688 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
689};
690
691// AutoThread automatically installs itself at construction
692// uninstalls at destruction, if a Thread object is
693// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200694//
695// NOTE: *** This class should only be used by tests ***
696//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200697class AutoThread : public Thread {
698 public:
699 AutoThread();
700 ~AutoThread() override;
701
702 private:
703 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
704};
705
706// AutoSocketServerThread automatically installs itself at
707// construction and uninstalls at destruction. If a Thread object is
708// already associated with the current OS thread, it is temporarily
709// disassociated and restored by the destructor.
710
711class AutoSocketServerThread : public Thread {
712 public:
713 explicit AutoSocketServerThread(SocketServer* ss);
714 ~AutoSocketServerThread() override;
715
716 private:
717 rtc::Thread* old_thread_;
718
719 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
720};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200721} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000722
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200723#endif // RTC_BASE_THREAD_H_