blob: e87248c01fbaae62c1e4b71fe5b0941c6c829c8d [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
Ali Tofigh7fa90572022-03-17 15:47:49 +010025#include "absl/strings/string_view.h"
26
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020027#if defined(WEBRTC_POSIX)
28#include <pthread.h>
29#endif
Henrik Boström2deee4b2022-01-20 11:58:05 +010030#include "absl/base/attributes.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020031#include "absl/functional/any_invocable.h"
Danil Chapovalov89313452019-11-29 12:56:43 +010032#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010033#include "api/task_queue/queued_task.h"
34#include "api/task_queue/task_queue_base.h"
Artem Titovc374d112022-06-16 21:27:45 +020035#include "api/task_queue/to_queued_task.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020036#include "api/units/time_delta.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020037#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020038#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020039#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020043#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020044#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010045#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020046
47#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020049#endif
50
Tommife041642021-04-07 10:08:28 +020051#if RTC_DCHECK_IS_ON
52// Counts how many blocking Thread::Invoke or Thread::Send calls are made from
53// within a scope and logs the number of blocking calls at the end of the scope.
54#define RTC_LOG_THREAD_BLOCK_COUNT() \
55 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
56 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
57 auto total = actual_block + could_block; \
58 if (total) { \
59 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
60 << " (actual=" << actual_block \
61 << ", could=" << could_block << ")"; \
62 } \
63 })
64
65// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
66// less than or equal to a specific value. Use to avoid regressing in the
67// number of blocking thread calls.
68// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
69// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020070#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
71 do { \
72 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
73 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
74 } while (0)
Tommife041642021-04-07 10:08:28 +020075#else
76#define RTC_LOG_THREAD_BLOCK_COUNT()
77#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
78#endif
79
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020080namespace rtc {
81
82class Thread;
83
Mirko Bonadei35214fc2019-09-23 14:54:28 +020084class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020085 public:
86 static const int kForever = -1;
87
88 // Singleton, constructor and destructor are private.
89 static ThreadManager* Instance();
90
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010091 static void Add(Thread* message_queue);
92 static void Remove(Thread* message_queue);
93 static void Clear(MessageHandler* handler);
94
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010095 // For testing purposes, for use with a simulated clock.
96 // Ensures that all message queues have processed delayed messages
97 // up until the current point in time.
98 static void ProcessAllMessageQueuesForTesting();
99
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200100 Thread* CurrentThread();
101 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +0100102 // Allows changing the current thread, this is intended for tests where we
103 // want to simulate multiple threads running on a single physical thread.
104 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200105
106 // Returns a thread object with its thread_ ivar set
107 // to whatever the OS uses to represent the thread.
108 // If there already *is* a Thread object corresponding to this thread,
109 // this method will return that. Otherwise it creates a new Thread
110 // object whose wrapped() method will return true, and whose
111 // handle will, on Win32, be opened with only synchronization privileges -
112 // if you need more privilegs, rather than changing this method, please
113 // write additional code to adjust the privileges, or call a different
114 // factory method of your own devising, because this one gets used in
115 // unexpected contexts (like inside browser plugins) and it would be a
116 // shame to break it. It is also conceivable on Win32 that we won't even
117 // be able to get synchronization privileges, in which case the result
118 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200119 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200120 void UnwrapCurrentThread();
121
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100122#if RTC_DCHECK_IS_ON
Artem Titov96e3b992021-07-26 16:03:14 +0200123 // Registers that a Send operation is to be performed between `source` and
124 // `target`, while checking that this does not cause a send cycle that could
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100125 // potentially cause a deadlock.
126 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
127#endif
128
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200129 private:
130 ThreadManager();
131 ~ThreadManager();
132
Byoungchan Lee14af7622022-01-12 05:24:58 +0900133 ThreadManager(const ThreadManager&) = delete;
134 ThreadManager& operator=(const ThreadManager&) = delete;
135
Sebastian Jansson178a6852020-01-14 11:12:26 +0100136 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100137 void AddInternal(Thread* message_queue);
138 void RemoveInternal(Thread* message_queue);
139 void ClearInternal(MessageHandler* handler);
140 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100141#if RTC_DCHECK_IS_ON
142 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
143#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100144
145 // This list contains all live Threads.
146 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
147
148 // Methods that don't modify the list of message queues may be called in a
149 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
150 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200151 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100152 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100153#if RTC_DCHECK_IS_ON
154 // Represents all thread seand actions by storing all send targets per thread.
155 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
156 // since we will trigger a CHECK failure if a cycle is introduced.
157 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
158#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100159
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200160#if defined(WEBRTC_POSIX)
161 pthread_key_t key_;
162#endif
163
164#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100165 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200167};
168
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200169// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
170
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100171class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700172 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100173 static const int kForever = -1;
174
175 // Create a new Thread and optionally assign it to the passed
176 // SocketServer. Subclasses that override Clear should pass false for
177 // init_queue and call DoInit() from their constructor to prevent races
178 // with the ThreadManager using the object while the vtable is still
179 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200180 explicit Thread(SocketServer* ss);
181 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100182
Taylor Brandstetter08672602018-03-02 15:20:33 -0800183 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200184 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800185 // instantiated class, which avoids a vptr data race.
186 Thread(SocketServer* ss, bool do_init);
187 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200188
189 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
190 // guarantee Stop() is explicitly called before the subclass is destroyed).
191 // This is required to avoid a data race between the destructor modifying the
192 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100193
194 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
195 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
196 // between the destructor modifying the vtable, and the ThreadManager
197 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 ~Thread() override;
199
Byoungchan Lee14af7622022-01-12 05:24:58 +0900200 Thread(const Thread&) = delete;
201 Thread& operator=(const Thread&) = delete;
202
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200203 static std::unique_ptr<Thread> CreateWithSocketServer();
204 static std::unique_ptr<Thread> Create();
205 static Thread* Current();
206
207 // Used to catch performance regressions. Use this to disallow blocking calls
208 // (Invoke) for a given scope. If a synchronous call is made while this is in
209 // effect, an assert will be triggered.
210 // Note that this is a single threaded class.
211 class ScopedDisallowBlockingCalls {
212 public:
213 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100214 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
215 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
216 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200218
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200219 private:
220 Thread* const thread_;
221 const bool previous_state_;
222 };
223
Tommife041642021-04-07 10:08:28 +0200224#if RTC_DCHECK_IS_ON
225 class ScopedCountBlockingCalls {
226 public:
227 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
228 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
229 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
230 delete;
231 ~ScopedCountBlockingCalls();
232
233 uint32_t GetBlockingCallCount() const;
234 uint32_t GetCouldBeBlockingCallCount() const;
235 uint32_t GetTotalBlockedCallCount() const;
236
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200237 void set_minimum_call_count_for_callback(uint32_t minimum) {
238 min_blocking_calls_for_callback_ = minimum;
239 }
240
Tommife041642021-04-07 10:08:28 +0200241 private:
242 Thread* const thread_;
243 const uint32_t base_blocking_call_count_;
244 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200245 // The minimum number of blocking calls required in order to issue the
246 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
247 // tame log spam.
248 // By default we always issue the callback, regardless of callback count.
249 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200250 std::function<void(uint32_t, uint32_t)> result_callback_;
251 };
252
253 uint32_t GetBlockingCallCount() const;
254 uint32_t GetCouldBeBlockingCallCount() const;
255#endif
256
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100257 SocketServer* socketserver();
258
259 // Note: The behavior of Thread has changed. When a thread is stopped,
260 // futher Posts and Sends will fail. However, any pending Sends and *ready*
261 // Posts (as opposed to unexpired delayed Posts) will be delivered before
262 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
263 // we eliminate the race condition when an MessageHandler and Thread
264 // may be destroyed independently of each other.
265 virtual void Quit();
266 virtual bool IsQuitting();
267 virtual void Restart();
268 // Not all message queues actually process messages (such as SignalThread).
269 // In those cases, it's important to know, before posting, that it won't be
270 // Processed. Normally, this would be true until IsQuitting() is true.
271 virtual bool IsProcessingMessagesForTesting();
272
273 // Get() will process I/O until:
274 // 1) A message is available (returns true)
275 // 2) cmsWait seconds have elapsed (returns false)
276 // 3) Stop() is called (returns false)
277 virtual bool Get(Message* pmsg,
278 int cmsWait = kForever,
279 bool process_io = true);
280 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Artem Titov96e3b992021-07-26 16:03:14 +0200281 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100282 virtual void Post(const Location& posted_from,
283 MessageHandler* phandler,
284 uint32_t id = 0,
285 MessageData* pdata = nullptr,
286 bool time_sensitive = false);
287 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100288 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100289 MessageHandler* phandler,
290 uint32_t id = 0,
291 MessageData* pdata = nullptr);
292 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100293 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100294 MessageHandler* phandler,
295 uint32_t id = 0,
296 MessageData* pdata = nullptr);
297 virtual void Clear(MessageHandler* phandler,
298 uint32_t id = MQID_ANY,
299 MessageList* removed = nullptr);
300 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100301
302 // Amount of time until the next message can be retrieved
303 virtual int GetDelay();
304
305 bool empty() const { return size() == 0u; }
306 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100307 CritScope cs(&crit_);
308 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100309 }
310
311 // Internally posts a message which causes the doomed object to be deleted
312 template <class T>
313 void Dispose(T* doomed) {
314 if (doomed) {
315 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
316 }
317 }
318
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319 bool IsCurrent() const;
320
321 // Sleeps the calling thread for the specified number of milliseconds, during
322 // which time no processing is performed. Returns false if sleeping was
323 // interrupted by a signal (POSIX only).
324 static bool SleepMs(int millis);
325
326 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200327 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200328 const std::string& name() const { return name_; }
Ali Tofigh7fa90572022-03-17 15:47:49 +0100329 bool SetName(absl::string_view name, const void* obj);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200330
Harald Alvestrandba694422021-01-27 21:52:14 +0000331 // Sets the expected processing time in ms. The thread will write
332 // log messages when Invoke() takes more time than this.
333 // Default is 50 ms.
334 void SetDispatchWarningMs(int deadline);
335
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200336 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200337 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200338
339 // Tells the thread to stop and waits until it is joined.
340 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100341 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200342 // underlying OS thread.
343 virtual void Stop();
344
345 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
346 // work, override Run(). To receive and dispatch messages, call
347 // ProcessMessages occasionally.
348 virtual void Run();
349
350 virtual void Send(const Location& posted_from,
351 MessageHandler* phandler,
352 uint32_t id = 0,
353 MessageData* pdata = nullptr);
354
355 // Convenience method to invoke a functor on another thread. Caller must
Artem Titov96e3b992021-07-26 16:03:14 +0200356 // provide the `ReturnT` template argument, which cannot (easily) be deduced.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200357 // Uses Send() internally, which blocks the current thread until execution
358 // is complete.
359 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
360 // &MyFunctionReturningBool);
361 // NOTE: This function can only be called when synchronous calls are allowed.
362 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100363 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
364 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100365 template <
366 class ReturnT,
367 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
368 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
369 ReturnT result;
370 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
371 return result;
372 }
373
374 template <
375 class ReturnT,
376 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
377 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
378 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200379 }
380
Artem Titov96e3b992021-07-26 16:03:14 +0200381 // Allows invoke to specified `thread`. Thread never will be dereferenced and
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200382 // will be used only for reference-based comparison, so instance can be safely
Mirko Bonadei481e3452021-07-30 13:57:25 +0200383 // deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200384 // nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200385 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200386
Mirko Bonadei481e3452021-07-30 13:57:25 +0200387 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200388 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200389 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200390 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
391 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200392 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200393 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200394 bool IsInvokeToThreadAllowed(rtc::Thread* target);
395
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100396 // From TaskQueueBase
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200397 void Delete() override;
398 void PostTask(absl::AnyInvocable<void() &&> task) override;
399 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
400 webrtc::TimeDelta delay) override;
401 void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
402 webrtc::TimeDelta delay) override;
403
404 // Legacy TaskQueueBase methods, do not use in new code.
405 // TODO(bugs.webrtc.org/14245): Delete when all code that use rtc::Thread
406 // directly is updated to use PostTask methods above.
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100407 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
408 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
409 uint32_t milliseconds) override;
Henrik Boströmcf9899c2022-01-20 09:46:16 +0100410 void PostDelayedHighPrecisionTask(std::unique_ptr<webrtc::QueuedTask> task,
411 uint32_t milliseconds) override;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100412
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200413 // Legacy helper method, do not use in new code.
414 // TODO(bugs.webrtc.org/14245): Delete when all code that use rtc::Thread
415 // directly is updated to use PostTask methods above.
416 ABSL_DEPRECATED("Pass delay as webrtc::TimeDelta type")
417 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
418 uint32_t milliseconds) {
419 PostDelayedTask(std::move(task), webrtc::TimeDelta::Millis(milliseconds));
Henrik Boström2deee4b2022-01-20 11:58:05 +0100420 }
421
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200422 // ProcessMessages will process I/O and dispatch messages until:
423 // 1) cms milliseconds have elapsed (returns true)
424 // 2) Stop() is called (returns false)
425 bool ProcessMessages(int cms);
426
427 // Returns true if this is a thread that we created using the standard
428 // constructor, false if it was created by a call to
429 // ThreadManager::WrapCurrentThread(). The main thread of an application
430 // is generally not owned, since the OS representation of the thread
431 // obviously exists before we can get to it.
432 // You cannot call Start on non-owned threads.
433 bool IsOwned();
434
Tommi51492422017-12-04 15:18:23 +0100435 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200436 //
437 // DANGER: this is a terrible public API. Most callers that might want to
438 // call this likely do not have enough control/knowledge of the Thread in
439 // question to guarantee that the returned value remains true for the duration
440 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100441 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200442
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200443 // These functions are public to avoid injecting test hooks. Don't call them
444 // outside of tests.
445 // This method should be called when thread is created using non standard
446 // method, like derived implementation of rtc::Thread and it can not be
447 // started by calling Start(). This will set started flag to true and
448 // owned to false. This must be called from the current thread.
449 bool WrapCurrent();
450 void UnwrapCurrent();
451
Karl Wiberg32562252019-02-21 13:38:30 +0100452 // Sets the per-thread allow-blocking-calls flag to false; this is
453 // irrevocable. Must be called on this thread.
454 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
455
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200456 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100457 class CurrentThreadSetter : CurrentTaskQueueSetter {
458 public:
459 explicit CurrentThreadSetter(Thread* thread)
460 : CurrentTaskQueueSetter(thread),
461 manager_(rtc::ThreadManager::Instance()),
462 previous_(manager_->CurrentThread()) {
463 manager_->ChangeCurrentThreadForTest(thread);
464 }
465 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
466
467 private:
468 rtc::ThreadManager* const manager_;
469 rtc::Thread* const previous_;
470 };
471
Sebastian Jansson61380c02020-01-17 14:46:08 +0100472 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
473 // with the same trigger time are processed in num_ (FIFO) order.
474 class DelayedMessage {
475 public:
476 DelayedMessage(int64_t delay,
477 int64_t run_time_ms,
478 uint32_t num,
479 const Message& msg)
480 : delay_ms_(delay),
481 run_time_ms_(run_time_ms),
482 message_number_(num),
483 msg_(msg) {}
484
485 bool operator<(const DelayedMessage& dmsg) const {
486 return (dmsg.run_time_ms_ < run_time_ms_) ||
487 ((dmsg.run_time_ms_ == run_time_ms_) &&
488 (dmsg.message_number_ < message_number_));
489 }
490
491 int64_t delay_ms_; // for debugging
492 int64_t run_time_ms_;
493 // Monotonicaly incrementing number used for ordering of messages
494 // targeted to execute at the same time.
495 uint32_t message_number_;
496 Message msg_;
497 };
498
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100499 class PriorityQueue : public std::priority_queue<DelayedMessage> {
500 public:
501 container_type& container() { return c; }
502 void reheap() { make_heap(c.begin(), c.end(), comp); }
503 };
504
505 void DoDelayPost(const Location& posted_from,
506 int64_t cmsDelay,
507 int64_t tstamp,
508 MessageHandler* phandler,
509 uint32_t id,
510 MessageData* pdata);
511
512 // Perform initialization, subclasses must call this from their constructor
513 // if false was passed as init_queue to the Thread constructor.
514 void DoInit();
515
516 // Does not take any lock. Must be called either while holding crit_, or by
517 // the destructor (by definition, the latter has exclusive access).
518 void ClearInternal(MessageHandler* phandler,
519 uint32_t id,
520 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
521
522 // Perform cleanup; subclasses must call this from the destructor,
523 // and are not expected to actually hold the lock.
524 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
525
526 void WakeUpSocketServer();
527
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200528 // Same as WrapCurrent except that it never fails as it does not try to
529 // acquire the synchronization access of the thread. The caller should never
530 // call Stop() or Join() on this thread.
531 void SafeWrapCurrent();
532
533 // Blocks the calling thread until this thread has terminated.
534 void Join();
535
536 static void AssertBlockingIsAllowedOnCurrentThread();
537
538 friend class ScopedDisallowBlockingCalls;
539
Markus Handell3cb525b2020-07-16 16:16:09 +0200540 RecursiveCriticalSection* CritForTest() { return &crit_; }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100541
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200542 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000543 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
544
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100545 class QueuedTaskHandler final : public MessageHandler {
546 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200547 QueuedTaskHandler() {}
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100548 void OnMessage(Message* msg) override;
549 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800550
Karl Wiberg32562252019-02-21 13:38:30 +0100551 // Sets the per-thread allow-blocking-calls flag and returns the previous
552 // value. Must be called on this thread.
553 bool SetAllowBlockingCalls(bool allow);
554
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200555#if defined(WEBRTC_WIN)
556 static DWORD WINAPI PreRun(LPVOID context);
557#else
Yves Gerey665174f2018-06-19 15:03:05 +0200558 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200559#endif
560
561 // ThreadManager calls this instead WrapCurrent() because
562 // ThreadManager::Instance() cannot be used while ThreadManager is
563 // being created.
564 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200565 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200566 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
567 bool need_synchronize_access);
568
Tommi51492422017-12-04 15:18:23 +0100569 // Return true if the thread is currently running.
570 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200571
Danil Chapovalov89313452019-11-29 12:56:43 +0100572 void InvokeInternal(const Location& posted_from,
573 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200574
Tommi6866dc72020-05-15 10:11:56 +0200575 // Called by the ThreadManager when being set as the current thread.
576 void EnsureIsCurrentTaskQueue();
577
578 // Called by the ThreadManager when being unset as the current thread.
579 void ClearCurrentTaskQueue();
580
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100581 bool fPeekKeep_;
582 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100583 MessageList messages_ RTC_GUARDED_BY(crit_);
584 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
585 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200586#if RTC_DCHECK_IS_ON
587 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
588 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200589 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
590 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
591#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200592 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100593 bool fInitialized_;
594 bool fDestroyed_;
595
Niels Möller7a669002022-06-27 09:47:02 +0200596 std::atomic<int> stop_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100597
598 // The SocketServer might not be owned by Thread.
599 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200600 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100601 std::unique_ptr<SocketServer> own_ss_;
602
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200603 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100604
Jonas Olssona4d87372019-07-05 19:08:33 +0200605 // TODO(tommi): Add thread checks for proper use of control methods.
606 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200607
608#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100609 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200610#endif
611
612#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100613 HANDLE thread_ = nullptr;
614 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200615#endif
616
Tommi51492422017-12-04 15:18:23 +0100617 // Indicates whether or not ownership of the worker thread lies with
618 // this instance or not. (i.e. owned_ == !wrapped).
619 // Must only be modified when the worker thread is not running.
620 bool owned_ = true;
621
622 // Only touched from the worker thread itself.
623 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200624
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100625 // Runs webrtc::QueuedTask posted to the Thread.
626 QueuedTaskHandler queued_task_handler_;
Tommi6866dc72020-05-15 10:11:56 +0200627 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
628 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100629
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200630 friend class ThreadManager;
631
Harald Alvestrandba694422021-01-27 21:52:14 +0000632 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200633};
634
635// AutoThread automatically installs itself at construction
636// uninstalls at destruction, if a Thread object is
637// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200638//
639// NOTE: *** This class should only be used by tests ***
640//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200641class AutoThread : public Thread {
642 public:
643 AutoThread();
644 ~AutoThread() override;
645
Byoungchan Lee14af7622022-01-12 05:24:58 +0900646 AutoThread(const AutoThread&) = delete;
647 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200648};
649
650// AutoSocketServerThread automatically installs itself at
651// construction and uninstalls at destruction. If a Thread object is
652// already associated with the current OS thread, it is temporarily
653// disassociated and restored by the destructor.
654
655class AutoSocketServerThread : public Thread {
656 public:
657 explicit AutoSocketServerThread(SocketServer* ss);
658 ~AutoSocketServerThread() override;
659
Byoungchan Lee14af7622022-01-12 05:24:58 +0900660 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
661 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
662
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200663 private:
664 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200665};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200666} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000667
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200668#endif // RTC_BASE_THREAD_H_