blob: 1519976f87a41c3e47a9ac4c12c98b527457ed3a [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>
Danil Chapovalov7c323ad2022-09-08 13:13:53 +020023#include <utility>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010024#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025
Ali Tofigh7fa90572022-03-17 15:47:49 +010026#include "absl/strings/string_view.h"
27
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020028#if defined(WEBRTC_POSIX)
29#include <pthread.h>
30#endif
Henrik Boström2deee4b2022-01-20 11:58:05 +010031#include "absl/base/attributes.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020032#include "absl/functional/any_invocable.h"
Danil Chapovalov89313452019-11-29 12:56:43 +010033#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010034#include "api/task_queue/task_queue_base.h"
Danil Chapovalov4bcf8092022-07-06 19:42:34 +020035#include "api/units/time_delta.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020036#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020037#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020038#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080039#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020042#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020043#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010044#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020045
46#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020048#endif
49
Tommife041642021-04-07 10:08:28 +020050#if RTC_DCHECK_IS_ON
Danil Chapovalov7c323ad2022-09-08 13:13:53 +020051// Counts how many `Thread::BlockingCall` are made from within a scope and logs
52// the number of blocking calls at the end of the scope.
Tommife041642021-04-07 10:08:28 +020053#define RTC_LOG_THREAD_BLOCK_COUNT() \
54 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
55 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
56 auto total = actual_block + could_block; \
57 if (total) { \
58 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
59 << " (actual=" << actual_block \
60 << ", could=" << could_block << ")"; \
61 } \
62 })
63
64// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
65// less than or equal to a specific value. Use to avoid regressing in the
66// number of blocking thread calls.
67// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
68// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020069#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
70 do { \
71 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
72 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
73 } while (0)
Tommife041642021-04-07 10:08:28 +020074#else
75#define RTC_LOG_THREAD_BLOCK_COUNT()
76#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
77#endif
78
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020079namespace rtc {
80
81class Thread;
82
Mirko Bonadei35214fc2019-09-23 14:54:28 +020083class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084 public:
85 static const int kForever = -1;
86
87 // Singleton, constructor and destructor are private.
88 static ThreadManager* Instance();
89
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010090 static void Add(Thread* message_queue);
91 static void Remove(Thread* message_queue);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010092
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);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100137 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100138#if RTC_DCHECK_IS_ON
139 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
140#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100141
142 // This list contains all live Threads.
143 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
144
145 // Methods that don't modify the list of message queues may be called in a
146 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
147 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200148 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100149 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100150#if RTC_DCHECK_IS_ON
151 // Represents all thread seand actions by storing all send targets per thread.
152 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
153 // since we will trigger a CHECK failure if a cycle is introduced.
154 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
155#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100156
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200157#if defined(WEBRTC_POSIX)
158 pthread_key_t key_;
159#endif
160
161#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100162 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200163#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164};
165
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
167
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100168class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700169 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100170 static const int kForever = -1;
171
172 // Create a new Thread and optionally assign it to the passed
173 // SocketServer. Subclasses that override Clear should pass false for
174 // init_queue and call DoInit() from their constructor to prevent races
175 // with the ThreadManager using the object while the vtable is still
176 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200177 explicit Thread(SocketServer* ss);
178 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100179
Taylor Brandstetter08672602018-03-02 15:20:33 -0800180 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200181 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800182 // instantiated class, which avoids a vptr data race.
183 Thread(SocketServer* ss, bool do_init);
184 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185
186 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
187 // guarantee Stop() is explicitly called before the subclass is destroyed).
188 // This is required to avoid a data race between the destructor modifying the
189 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100190
191 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
192 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
193 // between the destructor modifying the vtable, and the ThreadManager
194 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200195 ~Thread() override;
196
Byoungchan Lee14af7622022-01-12 05:24:58 +0900197 Thread(const Thread&) = delete;
198 Thread& operator=(const Thread&) = delete;
199
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200200 static std::unique_ptr<Thread> CreateWithSocketServer();
201 static std::unique_ptr<Thread> Create();
202 static Thread* Current();
203
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200204 // Used to catch performance regressions. Use this to disallow BlockingCall
205 // for a given scope. If a synchronous call is made while this is in
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200206 // effect, an assert will be triggered.
207 // Note that this is a single threaded class.
208 class ScopedDisallowBlockingCalls {
209 public:
210 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100211 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
212 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
213 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200214 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200215
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200216 private:
217 Thread* const thread_;
218 const bool previous_state_;
219 };
220
Tommife041642021-04-07 10:08:28 +0200221#if RTC_DCHECK_IS_ON
222 class ScopedCountBlockingCalls {
223 public:
224 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
225 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
226 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
227 delete;
228 ~ScopedCountBlockingCalls();
229
230 uint32_t GetBlockingCallCount() const;
231 uint32_t GetCouldBeBlockingCallCount() const;
232 uint32_t GetTotalBlockedCallCount() const;
233
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200234 void set_minimum_call_count_for_callback(uint32_t minimum) {
235 min_blocking_calls_for_callback_ = minimum;
236 }
237
Tommife041642021-04-07 10:08:28 +0200238 private:
239 Thread* const thread_;
240 const uint32_t base_blocking_call_count_;
241 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200242 // The minimum number of blocking calls required in order to issue the
243 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
244 // tame log spam.
245 // By default we always issue the callback, regardless of callback count.
246 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200247 std::function<void(uint32_t, uint32_t)> result_callback_;
248 };
249
250 uint32_t GetBlockingCallCount() const;
251 uint32_t GetCouldBeBlockingCallCount() const;
252#endif
253
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100254 SocketServer* socketserver();
255
256 // Note: The behavior of Thread has changed. When a thread is stopped,
257 // futher Posts and Sends will fail. However, any pending Sends and *ready*
258 // Posts (as opposed to unexpired delayed Posts) will be delivered before
259 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
260 // we eliminate the race condition when an MessageHandler and Thread
261 // may be destroyed independently of each other.
262 virtual void Quit();
263 virtual bool IsQuitting();
264 virtual void Restart();
265 // Not all message queues actually process messages (such as SignalThread).
266 // In those cases, it's important to know, before posting, that it won't be
267 // Processed. Normally, this would be true until IsQuitting() is true.
268 virtual bool IsProcessingMessagesForTesting();
269
Artem Titov96e3b992021-07-26 16:03:14 +0200270 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100271 virtual void Post(const Location& posted_from,
272 MessageHandler* phandler,
273 uint32_t id = 0,
274 MessageData* pdata = nullptr,
275 bool time_sensitive = false);
276 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100277 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100278 MessageHandler* phandler,
279 uint32_t id = 0,
280 MessageData* pdata = nullptr);
281 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100282 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100283 MessageHandler* phandler,
284 uint32_t id = 0,
285 MessageData* pdata = nullptr);
286 virtual void Clear(MessageHandler* phandler,
287 uint32_t id = MQID_ANY,
288 MessageList* removed = nullptr);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100289
290 // Amount of time until the next message can be retrieved
291 virtual int GetDelay();
292
293 bool empty() const { return size() == 0u; }
294 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100295 CritScope cs(&crit_);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200296 return messages_.size() + delayed_messages_.size();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100297 }
298
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200299 bool IsCurrent() const;
300
301 // Sleeps the calling thread for the specified number of milliseconds, during
302 // which time no processing is performed. Returns false if sleeping was
303 // interrupted by a signal (POSIX only).
304 static bool SleepMs(int millis);
305
306 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200307 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200308 const std::string& name() const { return name_; }
Ali Tofigh7fa90572022-03-17 15:47:49 +0100309 bool SetName(absl::string_view name, const void* obj);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200310
Harald Alvestrandba694422021-01-27 21:52:14 +0000311 // Sets the expected processing time in ms. The thread will write
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200312 // log messages when Dispatch() takes more time than this.
Harald Alvestrandba694422021-01-27 21:52:14 +0000313 // Default is 50 ms.
314 void SetDispatchWarningMs(int deadline);
315
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200316 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200317 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200318
319 // Tells the thread to stop and waits until it is joined.
320 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100321 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200322 // underlying OS thread.
323 virtual void Stop();
324
325 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
326 // work, override Run(). To receive and dispatch messages, call
327 // ProcessMessages occasionally.
328 virtual void Run();
329
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200330 // Convenience method to invoke a functor on another thread.
331 // Blocks the current thread until execution is complete.
332 // Ex: thread.BlockingCall([&] { result = MyFunctionReturningBool(); });
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200333 // NOTE: This function can only be called when synchronous calls are allowed.
334 // See ScopedDisallowBlockingCalls for details.
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200335 // NOTE: Blocking calls are DISCOURAGED, consider if what you're doing can
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100336 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200337 virtual void BlockingCall(FunctionView<void()> functor);
338
339 template <typename Functor,
340 typename ReturnT = std::invoke_result_t<Functor>,
341 typename = typename std::enable_if_t<!std::is_void_v<ReturnT>>>
342 ReturnT BlockingCall(Functor&& functor) {
Danil Chapovalov89313452019-11-29 12:56:43 +0100343 ReturnT result;
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200344 BlockingCall([&] { result = std::forward<Functor>(functor)(); });
Danil Chapovalov89313452019-11-29 12:56:43 +0100345 return result;
346 }
347
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200348 // Deprecated, use `BlockingCall` instead.
349 template <typename ReturnT>
Danil Chapovalov9e09a1f2022-09-08 18:38:10 +0200350 [[deprecated]] ReturnT Invoke(const Location& /*posted_from*/,
351 FunctionView<ReturnT()> functor) {
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200352 return BlockingCall(functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200353 }
354
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200355 // Allows BlockingCall to specified `thread`. Thread never will be
356 // dereferenced and will be used only for reference-based comparison, so
357 // instance can be safely deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON
358 // is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200359 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200360
Mirko Bonadei481e3452021-07-30 13:57:25 +0200361 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200362 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200363 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200364 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
365 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200366 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200367 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200368 bool IsInvokeToThreadAllowed(rtc::Thread* target);
369
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100370 // From TaskQueueBase
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200371 void Delete() override;
372 void PostTask(absl::AnyInvocable<void() &&> task) override;
373 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
374 webrtc::TimeDelta delay) override;
375 void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
376 webrtc::TimeDelta delay) override;
377
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200378 // ProcessMessages will process I/O and dispatch messages until:
379 // 1) cms milliseconds have elapsed (returns true)
380 // 2) Stop() is called (returns false)
381 bool ProcessMessages(int cms);
382
383 // Returns true if this is a thread that we created using the standard
384 // constructor, false if it was created by a call to
385 // ThreadManager::WrapCurrentThread(). The main thread of an application
386 // is generally not owned, since the OS representation of the thread
387 // obviously exists before we can get to it.
388 // You cannot call Start on non-owned threads.
389 bool IsOwned();
390
Tommi51492422017-12-04 15:18:23 +0100391 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200392 //
393 // DANGER: this is a terrible public API. Most callers that might want to
394 // call this likely do not have enough control/knowledge of the Thread in
395 // question to guarantee that the returned value remains true for the duration
396 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100397 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200398
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200399 // These functions are public to avoid injecting test hooks. Don't call them
400 // outside of tests.
401 // This method should be called when thread is created using non standard
402 // method, like derived implementation of rtc::Thread and it can not be
403 // started by calling Start(). This will set started flag to true and
404 // owned to false. This must be called from the current thread.
405 bool WrapCurrent();
406 void UnwrapCurrent();
407
Karl Wiberg32562252019-02-21 13:38:30 +0100408 // Sets the per-thread allow-blocking-calls flag to false; this is
409 // irrevocable. Must be called on this thread.
410 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
411
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200412 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100413 class CurrentThreadSetter : CurrentTaskQueueSetter {
414 public:
415 explicit CurrentThreadSetter(Thread* thread)
416 : CurrentTaskQueueSetter(thread),
417 manager_(rtc::ThreadManager::Instance()),
418 previous_(manager_->CurrentThread()) {
419 manager_->ChangeCurrentThreadForTest(thread);
420 }
421 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
422
423 private:
424 rtc::ThreadManager* const manager_;
425 rtc::Thread* const previous_;
426 };
427
Sebastian Jansson61380c02020-01-17 14:46:08 +0100428 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
429 // with the same trigger time are processed in num_ (FIFO) order.
430 class DelayedMessage {
431 public:
432 DelayedMessage(int64_t delay,
433 int64_t run_time_ms,
434 uint32_t num,
435 const Message& msg)
436 : delay_ms_(delay),
437 run_time_ms_(run_time_ms),
438 message_number_(num),
439 msg_(msg) {}
440
441 bool operator<(const DelayedMessage& dmsg) const {
442 return (dmsg.run_time_ms_ < run_time_ms_) ||
443 ((dmsg.run_time_ms_ == run_time_ms_) &&
444 (dmsg.message_number_ < message_number_));
445 }
446
447 int64_t delay_ms_; // for debugging
448 int64_t run_time_ms_;
449 // Monotonicaly incrementing number used for ordering of messages
450 // targeted to execute at the same time.
451 uint32_t message_number_;
452 Message msg_;
453 };
454
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100455 class PriorityQueue : public std::priority_queue<DelayedMessage> {
456 public:
457 container_type& container() { return c; }
458 void reheap() { make_heap(c.begin(), c.end(), comp); }
459 };
460
461 void DoDelayPost(const Location& posted_from,
462 int64_t cmsDelay,
463 int64_t tstamp,
464 MessageHandler* phandler,
465 uint32_t id,
466 MessageData* pdata);
467
468 // Perform initialization, subclasses must call this from their constructor
469 // if false was passed as init_queue to the Thread constructor.
470 void DoInit();
471
472 // Does not take any lock. Must be called either while holding crit_, or by
473 // the destructor (by definition, the latter has exclusive access).
474 void ClearInternal(MessageHandler* phandler,
475 uint32_t id,
476 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
477
478 // Perform cleanup; subclasses must call this from the destructor,
479 // and are not expected to actually hold the lock.
480 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
481
482 void WakeUpSocketServer();
483
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200484 // Same as WrapCurrent except that it never fails as it does not try to
485 // acquire the synchronization access of the thread. The caller should never
486 // call Stop() or Join() on this thread.
487 void SafeWrapCurrent();
488
489 // Blocks the calling thread until this thread has terminated.
490 void Join();
491
492 static void AssertBlockingIsAllowedOnCurrentThread();
493
494 friend class ScopedDisallowBlockingCalls;
495
496 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000497 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
498
Danil Chapovalov207f8532022-08-24 12:19:46 +0200499 // Get() will process I/O until:
500 // 1) A message is available (returns true)
501 // 2) cmsWait seconds have elapsed (returns false)
502 // 3) Stop() is called (returns false)
503 virtual bool Get(Message* pmsg,
504 int cmsWait = kForever,
505 bool process_io = true);
506 virtual void Dispatch(Message* pmsg);
507
Karl Wiberg32562252019-02-21 13:38:30 +0100508 // Sets the per-thread allow-blocking-calls flag and returns the previous
509 // value. Must be called on this thread.
510 bool SetAllowBlockingCalls(bool allow);
511
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200512#if defined(WEBRTC_WIN)
513 static DWORD WINAPI PreRun(LPVOID context);
514#else
Yves Gerey665174f2018-06-19 15:03:05 +0200515 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200516#endif
517
518 // ThreadManager calls this instead WrapCurrent() because
519 // ThreadManager::Instance() cannot be used while ThreadManager is
520 // being created.
521 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200522 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200523 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
524 bool need_synchronize_access);
525
Tommi51492422017-12-04 15:18:23 +0100526 // Return true if the thread is currently running.
527 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200528
Tommi6866dc72020-05-15 10:11:56 +0200529 // Called by the ThreadManager when being set as the current thread.
530 void EnsureIsCurrentTaskQueue();
531
532 // Called by the ThreadManager when being unset as the current thread.
533 void ClearCurrentTaskQueue();
534
Sebastian Jansson61380c02020-01-17 14:46:08 +0100535 MessageList messages_ RTC_GUARDED_BY(crit_);
536 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
537 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200538#if RTC_DCHECK_IS_ON
539 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
540 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200541 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
542 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
543#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200544 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100545 bool fInitialized_;
546 bool fDestroyed_;
547
Niels Möller7a669002022-06-27 09:47:02 +0200548 std::atomic<int> stop_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100549
550 // The SocketServer might not be owned by Thread.
551 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200552 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100553 std::unique_ptr<SocketServer> own_ss_;
554
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200555 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100556
Jonas Olssona4d87372019-07-05 19:08:33 +0200557 // TODO(tommi): Add thread checks for proper use of control methods.
558 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200559
560#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100561 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200562#endif
563
564#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100565 HANDLE thread_ = nullptr;
566 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200567#endif
568
Tommi51492422017-12-04 15:18:23 +0100569 // Indicates whether or not ownership of the worker thread lies with
570 // this instance or not. (i.e. owned_ == !wrapped).
571 // Must only be modified when the worker thread is not running.
572 bool owned_ = true;
573
574 // Only touched from the worker thread itself.
575 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200576
Tommi6866dc72020-05-15 10:11:56 +0200577 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
578 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100579
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200580 friend class ThreadManager;
581
Harald Alvestrandba694422021-01-27 21:52:14 +0000582 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200583};
584
585// AutoThread automatically installs itself at construction
586// uninstalls at destruction, if a Thread object is
587// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200588//
589// NOTE: *** This class should only be used by tests ***
590//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200591class AutoThread : public Thread {
592 public:
593 AutoThread();
594 ~AutoThread() override;
595
Byoungchan Lee14af7622022-01-12 05:24:58 +0900596 AutoThread(const AutoThread&) = delete;
597 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200598};
599
600// AutoSocketServerThread automatically installs itself at
601// construction and uninstalls at destruction. If a Thread object is
602// already associated with the current OS thread, it is temporarily
603// disassociated and restored by the destructor.
604
605class AutoSocketServerThread : public Thread {
606 public:
607 explicit AutoSocketServerThread(SocketServer* ss);
608 ~AutoSocketServerThread() override;
609
Byoungchan Lee14af7622022-01-12 05:24:58 +0900610 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
611 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
612
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200613 private:
614 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200615};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200616} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000617
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200618#endif // RTC_BASE_THREAD_H_