blob: 52df554f24c356e71eebef9fefda296fa21f02a5 [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/task_queue_base.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020034#include "api/units/time_delta.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020035#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020036#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020037#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020041#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020042#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010043#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020044
45#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020047#endif
48
Tommife041642021-04-07 10:08:28 +020049#if RTC_DCHECK_IS_ON
50// Counts how many blocking Thread::Invoke or Thread::Send calls are made from
51// within a scope and logs the number of blocking calls at the end of the scope.
52#define RTC_LOG_THREAD_BLOCK_COUNT() \
53 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
54 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
55 auto total = actual_block + could_block; \
56 if (total) { \
57 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
58 << " (actual=" << actual_block \
59 << ", could=" << could_block << ")"; \
60 } \
61 })
62
63// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
64// less than or equal to a specific value. Use to avoid regressing in the
65// number of blocking thread calls.
66// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
67// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020068#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
69 do { \
70 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
71 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
72 } while (0)
Tommife041642021-04-07 10:08:28 +020073#else
74#define RTC_LOG_THREAD_BLOCK_COUNT()
75#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
76#endif
77
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020078namespace rtc {
79
80class Thread;
81
Mirko Bonadei35214fc2019-09-23 14:54:28 +020082class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020083 public:
84 static const int kForever = -1;
85
86 // Singleton, constructor and destructor are private.
87 static ThreadManager* Instance();
88
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010089 static void Add(Thread* message_queue);
90 static void Remove(Thread* message_queue);
91 static void Clear(MessageHandler* handler);
92
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010093 // For testing purposes, for use with a simulated clock.
94 // Ensures that all message queues have processed delayed messages
95 // up until the current point in time.
96 static void ProcessAllMessageQueuesForTesting();
97
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020098 Thread* CurrentThread();
99 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +0100100 // Allows changing the current thread, this is intended for tests where we
101 // want to simulate multiple threads running on a single physical thread.
102 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200103
104 // Returns a thread object with its thread_ ivar set
105 // to whatever the OS uses to represent the thread.
106 // If there already *is* a Thread object corresponding to this thread,
107 // this method will return that. Otherwise it creates a new Thread
108 // object whose wrapped() method will return true, and whose
109 // handle will, on Win32, be opened with only synchronization privileges -
110 // if you need more privilegs, rather than changing this method, please
111 // write additional code to adjust the privileges, or call a different
112 // factory method of your own devising, because this one gets used in
113 // unexpected contexts (like inside browser plugins) and it would be a
114 // shame to break it. It is also conceivable on Win32 that we won't even
115 // be able to get synchronization privileges, in which case the result
116 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200117 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200118 void UnwrapCurrentThread();
119
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100120#if RTC_DCHECK_IS_ON
Artem Titov96e3b992021-07-26 16:03:14 +0200121 // Registers that a Send operation is to be performed between `source` and
122 // `target`, while checking that this does not cause a send cycle that could
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100123 // potentially cause a deadlock.
124 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
125#endif
126
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127 private:
128 ThreadManager();
129 ~ThreadManager();
130
Byoungchan Lee14af7622022-01-12 05:24:58 +0900131 ThreadManager(const ThreadManager&) = delete;
132 ThreadManager& operator=(const ThreadManager&) = delete;
133
Sebastian Jansson178a6852020-01-14 11:12:26 +0100134 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100135 void AddInternal(Thread* message_queue);
136 void RemoveInternal(Thread* message_queue);
137 void ClearInternal(MessageHandler* handler);
138 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100139#if RTC_DCHECK_IS_ON
140 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
141#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100142
143 // This list contains all live Threads.
144 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
145
146 // Methods that don't modify the list of message queues may be called in a
147 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
148 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200149 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100150 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100151#if RTC_DCHECK_IS_ON
152 // Represents all thread seand actions by storing all send targets per thread.
153 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
154 // since we will trigger a CHECK failure if a cycle is introduced.
155 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
156#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100157
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158#if defined(WEBRTC_POSIX)
159 pthread_key_t key_;
160#endif
161
162#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100163 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200165};
166
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200167// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
168
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100169class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700170 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100171 static const int kForever = -1;
172
173 // Create a new Thread and optionally assign it to the passed
174 // SocketServer. Subclasses that override Clear should pass false for
175 // init_queue and call DoInit() from their constructor to prevent races
176 // with the ThreadManager using the object while the vtable is still
177 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200178 explicit Thread(SocketServer* ss);
179 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100180
Taylor Brandstetter08672602018-03-02 15:20:33 -0800181 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200182 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800183 // instantiated class, which avoids a vptr data race.
184 Thread(SocketServer* ss, bool do_init);
185 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200186
187 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
188 // guarantee Stop() is explicitly called before the subclass is destroyed).
189 // This is required to avoid a data race between the destructor modifying the
190 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100191
192 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
193 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
194 // between the destructor modifying the vtable, and the ThreadManager
195 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200196 ~Thread() override;
197
Byoungchan Lee14af7622022-01-12 05:24:58 +0900198 Thread(const Thread&) = delete;
199 Thread& operator=(const Thread&) = delete;
200
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200201 static std::unique_ptr<Thread> CreateWithSocketServer();
202 static std::unique_ptr<Thread> Create();
203 static Thread* Current();
204
205 // Used to catch performance regressions. Use this to disallow blocking calls
206 // (Invoke) for a given scope. If a synchronous call is made while this is in
207 // effect, an assert will be triggered.
208 // Note that this is a single threaded class.
209 class ScopedDisallowBlockingCalls {
210 public:
211 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100212 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
213 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
214 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200216
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 private:
218 Thread* const thread_;
219 const bool previous_state_;
220 };
221
Tommife041642021-04-07 10:08:28 +0200222#if RTC_DCHECK_IS_ON
223 class ScopedCountBlockingCalls {
224 public:
225 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
226 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
227 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
228 delete;
229 ~ScopedCountBlockingCalls();
230
231 uint32_t GetBlockingCallCount() const;
232 uint32_t GetCouldBeBlockingCallCount() const;
233 uint32_t GetTotalBlockedCallCount() const;
234
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200235 void set_minimum_call_count_for_callback(uint32_t minimum) {
236 min_blocking_calls_for_callback_ = minimum;
237 }
238
Tommife041642021-04-07 10:08:28 +0200239 private:
240 Thread* const thread_;
241 const uint32_t base_blocking_call_count_;
242 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200243 // The minimum number of blocking calls required in order to issue the
244 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
245 // tame log spam.
246 // By default we always issue the callback, regardless of callback count.
247 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200248 std::function<void(uint32_t, uint32_t)> result_callback_;
249 };
250
251 uint32_t GetBlockingCallCount() const;
252 uint32_t GetCouldBeBlockingCallCount() const;
253#endif
254
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100255 SocketServer* socketserver();
256
257 // Note: The behavior of Thread has changed. When a thread is stopped,
258 // futher Posts and Sends will fail. However, any pending Sends and *ready*
259 // Posts (as opposed to unexpired delayed Posts) will be delivered before
260 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
261 // we eliminate the race condition when an MessageHandler and Thread
262 // may be destroyed independently of each other.
263 virtual void Quit();
264 virtual bool IsQuitting();
265 virtual void Restart();
266 // Not all message queues actually process messages (such as SignalThread).
267 // In those cases, it's important to know, before posting, that it won't be
268 // Processed. Normally, this would be true until IsQuitting() is true.
269 virtual bool IsProcessingMessagesForTesting();
270
Artem Titov96e3b992021-07-26 16:03:14 +0200271 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100272 virtual void Post(const Location& posted_from,
273 MessageHandler* phandler,
274 uint32_t id = 0,
275 MessageData* pdata = nullptr,
276 bool time_sensitive = false);
277 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100278 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100279 MessageHandler* phandler,
280 uint32_t id = 0,
281 MessageData* pdata = nullptr);
282 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100283 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100284 MessageHandler* phandler,
285 uint32_t id = 0,
286 MessageData* pdata = nullptr);
287 virtual void Clear(MessageHandler* phandler,
288 uint32_t id = MQID_ANY,
289 MessageList* removed = nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100290
291 // Amount of time until the next message can be retrieved
292 virtual int GetDelay();
293
294 bool empty() const { return size() == 0u; }
295 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100296 CritScope cs(&crit_);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200297 return messages_.size() + delayed_messages_.size();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100298 }
299
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200300 bool IsCurrent() const;
301
302 // Sleeps the calling thread for the specified number of milliseconds, during
303 // which time no processing is performed. Returns false if sleeping was
304 // interrupted by a signal (POSIX only).
305 static bool SleepMs(int millis);
306
307 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200308 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200309 const std::string& name() const { return name_; }
Ali Tofigh7fa90572022-03-17 15:47:49 +0100310 bool SetName(absl::string_view name, const void* obj);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200311
Harald Alvestrandba694422021-01-27 21:52:14 +0000312 // Sets the expected processing time in ms. The thread will write
313 // log messages when Invoke() takes more time than this.
314 // Default is 50 ms.
315 void SetDispatchWarningMs(int deadline);
316
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200317 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200318 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319
320 // Tells the thread to stop and waits until it is joined.
321 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100322 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200323 // underlying OS thread.
324 virtual void Stop();
325
326 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
327 // work, override Run(). To receive and dispatch messages, call
328 // ProcessMessages occasionally.
329 virtual void Run();
330
331 virtual void Send(const Location& posted_from,
332 MessageHandler* phandler,
333 uint32_t id = 0,
334 MessageData* pdata = nullptr);
335
336 // Convenience method to invoke a functor on another thread. Caller must
Artem Titov96e3b992021-07-26 16:03:14 +0200337 // provide the `ReturnT` template argument, which cannot (easily) be deduced.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200338 // Uses Send() internally, which blocks the current thread until execution
339 // is complete.
340 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
341 // &MyFunctionReturningBool);
342 // NOTE: This function can only be called when synchronous calls are allowed.
343 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100344 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
345 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100346 template <
347 class ReturnT,
348 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
349 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
350 ReturnT result;
351 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
352 return result;
353 }
354
355 template <
356 class ReturnT,
357 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
358 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
359 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200360 }
361
Artem Titov96e3b992021-07-26 16:03:14 +0200362 // Allows invoke to specified `thread`. Thread never will be dereferenced and
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200363 // will be used only for reference-based comparison, so instance can be safely
Mirko Bonadei481e3452021-07-30 13:57:25 +0200364 // deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200365 // nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200366 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200367
Mirko Bonadei481e3452021-07-30 13:57:25 +0200368 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200369 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200370 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200371 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
372 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200373 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200374 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200375 bool IsInvokeToThreadAllowed(rtc::Thread* target);
376
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100377 // From TaskQueueBase
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200378 void Delete() override;
379 void PostTask(absl::AnyInvocable<void() &&> task) override;
380 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
381 webrtc::TimeDelta delay) override;
382 void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
383 webrtc::TimeDelta delay) override;
384
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200385 // ProcessMessages will process I/O and dispatch messages until:
386 // 1) cms milliseconds have elapsed (returns true)
387 // 2) Stop() is called (returns false)
388 bool ProcessMessages(int cms);
389
390 // Returns true if this is a thread that we created using the standard
391 // constructor, false if it was created by a call to
392 // ThreadManager::WrapCurrentThread(). The main thread of an application
393 // is generally not owned, since the OS representation of the thread
394 // obviously exists before we can get to it.
395 // You cannot call Start on non-owned threads.
396 bool IsOwned();
397
Tommi51492422017-12-04 15:18:23 +0100398 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200399 //
400 // DANGER: this is a terrible public API. Most callers that might want to
401 // call this likely do not have enough control/knowledge of the Thread in
402 // question to guarantee that the returned value remains true for the duration
403 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100404 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200405
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406 // These functions are public to avoid injecting test hooks. Don't call them
407 // outside of tests.
408 // This method should be called when thread is created using non standard
409 // method, like derived implementation of rtc::Thread and it can not be
410 // started by calling Start(). This will set started flag to true and
411 // owned to false. This must be called from the current thread.
412 bool WrapCurrent();
413 void UnwrapCurrent();
414
Karl Wiberg32562252019-02-21 13:38:30 +0100415 // Sets the per-thread allow-blocking-calls flag to false; this is
416 // irrevocable. Must be called on this thread.
417 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
418
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200419 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100420 class CurrentThreadSetter : CurrentTaskQueueSetter {
421 public:
422 explicit CurrentThreadSetter(Thread* thread)
423 : CurrentTaskQueueSetter(thread),
424 manager_(rtc::ThreadManager::Instance()),
425 previous_(manager_->CurrentThread()) {
426 manager_->ChangeCurrentThreadForTest(thread);
427 }
428 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
429
430 private:
431 rtc::ThreadManager* const manager_;
432 rtc::Thread* const previous_;
433 };
434
Sebastian Jansson61380c02020-01-17 14:46:08 +0100435 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
436 // with the same trigger time are processed in num_ (FIFO) order.
437 class DelayedMessage {
438 public:
439 DelayedMessage(int64_t delay,
440 int64_t run_time_ms,
441 uint32_t num,
442 const Message& msg)
443 : delay_ms_(delay),
444 run_time_ms_(run_time_ms),
445 message_number_(num),
446 msg_(msg) {}
447
448 bool operator<(const DelayedMessage& dmsg) const {
449 return (dmsg.run_time_ms_ < run_time_ms_) ||
450 ((dmsg.run_time_ms_ == run_time_ms_) &&
451 (dmsg.message_number_ < message_number_));
452 }
453
454 int64_t delay_ms_; // for debugging
455 int64_t run_time_ms_;
456 // Monotonicaly incrementing number used for ordering of messages
457 // targeted to execute at the same time.
458 uint32_t message_number_;
459 Message msg_;
460 };
461
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100462 class PriorityQueue : public std::priority_queue<DelayedMessage> {
463 public:
464 container_type& container() { return c; }
465 void reheap() { make_heap(c.begin(), c.end(), comp); }
466 };
467
468 void DoDelayPost(const Location& posted_from,
469 int64_t cmsDelay,
470 int64_t tstamp,
471 MessageHandler* phandler,
472 uint32_t id,
473 MessageData* pdata);
474
475 // Perform initialization, subclasses must call this from their constructor
476 // if false was passed as init_queue to the Thread constructor.
477 void DoInit();
478
479 // Does not take any lock. Must be called either while holding crit_, or by
480 // the destructor (by definition, the latter has exclusive access).
481 void ClearInternal(MessageHandler* phandler,
482 uint32_t id,
483 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
484
485 // Perform cleanup; subclasses must call this from the destructor,
486 // and are not expected to actually hold the lock.
487 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
488
489 void WakeUpSocketServer();
490
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200491 // Same as WrapCurrent except that it never fails as it does not try to
492 // acquire the synchronization access of the thread. The caller should never
493 // call Stop() or Join() on this thread.
494 void SafeWrapCurrent();
495
496 // Blocks the calling thread until this thread has terminated.
497 void Join();
498
499 static void AssertBlockingIsAllowedOnCurrentThread();
500
501 friend class ScopedDisallowBlockingCalls;
502
503 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000504 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
505
Danil Chapovalov207f8532022-08-24 12:19:46 +0200506 // TODO(bugs.webrtc.org/9702): Delete when chromium stops overriding it.
507 // chromium's ThreadWrapper overrides it just to check it is never called.
508 virtual bool Peek(Message* pmsg, int cms_wait) {
509 RTC_DCHECK_NOTREACHED();
510 return false;
511 }
512 // Get() will process I/O until:
513 // 1) A message is available (returns true)
514 // 2) cmsWait seconds have elapsed (returns false)
515 // 3) Stop() is called (returns false)
516 virtual bool Get(Message* pmsg,
517 int cmsWait = kForever,
518 bool process_io = true);
519 virtual void Dispatch(Message* pmsg);
520
Karl Wiberg32562252019-02-21 13:38:30 +0100521 // Sets the per-thread allow-blocking-calls flag and returns the previous
522 // value. Must be called on this thread.
523 bool SetAllowBlockingCalls(bool allow);
524
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200525#if defined(WEBRTC_WIN)
526 static DWORD WINAPI PreRun(LPVOID context);
527#else
Yves Gerey665174f2018-06-19 15:03:05 +0200528 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200529#endif
530
531 // ThreadManager calls this instead WrapCurrent() because
532 // ThreadManager::Instance() cannot be used while ThreadManager is
533 // being created.
534 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200535 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200536 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
537 bool need_synchronize_access);
538
Tommi51492422017-12-04 15:18:23 +0100539 // Return true if the thread is currently running.
540 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200541
Danil Chapovalov89313452019-11-29 12:56:43 +0100542 void InvokeInternal(const Location& posted_from,
543 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200544
Tommi6866dc72020-05-15 10:11:56 +0200545 // Called by the ThreadManager when being set as the current thread.
546 void EnsureIsCurrentTaskQueue();
547
548 // Called by the ThreadManager when being unset as the current thread.
549 void ClearCurrentTaskQueue();
550
Sebastian Jansson61380c02020-01-17 14:46:08 +0100551 MessageList messages_ RTC_GUARDED_BY(crit_);
552 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
553 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200554#if RTC_DCHECK_IS_ON
555 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
556 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200557 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
558 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
559#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200560 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100561 bool fInitialized_;
562 bool fDestroyed_;
563
Niels Möller7a669002022-06-27 09:47:02 +0200564 std::atomic<int> stop_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100565
566 // The SocketServer might not be owned by Thread.
567 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200568 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100569 std::unique_ptr<SocketServer> own_ss_;
570
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200571 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100572
Jonas Olssona4d87372019-07-05 19:08:33 +0200573 // TODO(tommi): Add thread checks for proper use of control methods.
574 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200575
576#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100577 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200578#endif
579
580#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100581 HANDLE thread_ = nullptr;
582 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200583#endif
584
Tommi51492422017-12-04 15:18:23 +0100585 // Indicates whether or not ownership of the worker thread lies with
586 // this instance or not. (i.e. owned_ == !wrapped).
587 // Must only be modified when the worker thread is not running.
588 bool owned_ = true;
589
590 // Only touched from the worker thread itself.
591 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200592
Tommi6866dc72020-05-15 10:11:56 +0200593 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
594 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100595
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200596 friend class ThreadManager;
597
Harald Alvestrandba694422021-01-27 21:52:14 +0000598 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200599};
600
601// AutoThread automatically installs itself at construction
602// uninstalls at destruction, if a Thread object is
603// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200604//
605// NOTE: *** This class should only be used by tests ***
606//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200607class AutoThread : public Thread {
608 public:
609 AutoThread();
610 ~AutoThread() override;
611
Byoungchan Lee14af7622022-01-12 05:24:58 +0900612 AutoThread(const AutoThread&) = delete;
613 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200614};
615
616// AutoSocketServerThread automatically installs itself at
617// construction and uninstalls at destruction. If a Thread object is
618// already associated with the current OS thread, it is temporarily
619// disassociated and restored by the destructor.
620
621class AutoSocketServerThread : public Thread {
622 public:
623 explicit AutoSocketServerThread(SocketServer* ss);
624 ~AutoSocketServerThread() override;
625
Byoungchan Lee14af7622022-01-12 05:24:58 +0900626 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
627 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
628
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200629 private:
630 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200631};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200632} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000633
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200634#endif // RTC_BASE_THREAD_H_