blob: b2f8e353b6e2e68d9ee68f219b227bd914f74fbc [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_THREAD_H_
12#define RTC_BASE_THREAD_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <list>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010017#include <map>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#include <memory>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010019#include <queue>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010020#include <set>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020021#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020022#include <type_traits>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010023#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025#if defined(WEBRTC_POSIX)
26#include <pthread.h>
27#endif
Danil Chapovalov89313452019-11-29 12:56:43 +010028#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010029#include "api/task_queue/queued_task.h"
30#include "api/task_queue/task_queue_base.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020031#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020032#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020037#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020038#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010039#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020040
41#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043#endif
44
Tommife041642021-04-07 10:08:28 +020045#if RTC_DCHECK_IS_ON
46// Counts how many blocking Thread::Invoke or Thread::Send calls are made from
47// within a scope and logs the number of blocking calls at the end of the scope.
48#define RTC_LOG_THREAD_BLOCK_COUNT() \
49 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
50 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
51 auto total = actual_block + could_block; \
52 if (total) { \
53 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
54 << " (actual=" << actual_block \
55 << ", could=" << could_block << ")"; \
56 } \
57 })
58
59// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
60// less than or equal to a specific value. Use to avoid regressing in the
61// number of blocking thread calls.
62// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
63// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020064#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
65 do { \
66 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
67 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
68 } while (0)
Tommife041642021-04-07 10:08:28 +020069#else
70#define RTC_LOG_THREAD_BLOCK_COUNT()
71#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
72#endif
73
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020074namespace rtc {
75
76class Thread;
77
Henrik Boströmba4dcc32019-02-28 09:34:06 +010078namespace rtc_thread_internal {
79
Niels Möllerf13a0962019-05-17 10:15:06 +020080class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010081 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020082 virtual void Run() = 0;
83};
84
85template <class FunctorT>
86class MessageWithFunctor final : public MessageLikeTask {
87 public:
88 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010089 : functor_(std::forward<FunctorT>(functor)) {}
90
Byoungchan Lee14af7622022-01-12 05:24:58 +090091 MessageWithFunctor(const MessageWithFunctor&) = delete;
92 MessageWithFunctor& operator=(const MessageWithFunctor&) = delete;
93
Niels Möllerf13a0962019-05-17 10:15:06 +020094 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010095
96 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020097 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010098
99 typename std::remove_reference<FunctorT>::type functor_;
Niels Möllerf13a0962019-05-17 10:15:06 +0200100};
101
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100102} // namespace rtc_thread_internal
103
Mirko Bonadei35214fc2019-09-23 14:54:28 +0200104class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200105 public:
106 static const int kForever = -1;
107
108 // Singleton, constructor and destructor are private.
109 static ThreadManager* Instance();
110
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100111 static void Add(Thread* message_queue);
112 static void Remove(Thread* message_queue);
113 static void Clear(MessageHandler* handler);
114
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100115 // For testing purposes, for use with a simulated clock.
116 // Ensures that all message queues have processed delayed messages
117 // up until the current point in time.
118 static void ProcessAllMessageQueuesForTesting();
119
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200120 Thread* CurrentThread();
121 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +0100122 // Allows changing the current thread, this is intended for tests where we
123 // want to simulate multiple threads running on a single physical thread.
124 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200125
126 // Returns a thread object with its thread_ ivar set
127 // to whatever the OS uses to represent the thread.
128 // If there already *is* a Thread object corresponding to this thread,
129 // this method will return that. Otherwise it creates a new Thread
130 // object whose wrapped() method will return true, and whose
131 // handle will, on Win32, be opened with only synchronization privileges -
132 // if you need more privilegs, rather than changing this method, please
133 // write additional code to adjust the privileges, or call a different
134 // factory method of your own devising, because this one gets used in
135 // unexpected contexts (like inside browser plugins) and it would be a
136 // shame to break it. It is also conceivable on Win32 that we won't even
137 // be able to get synchronization privileges, in which case the result
138 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200139 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140 void UnwrapCurrentThread();
141
Niels Moller9d1840c2019-05-21 07:26:37 +0000142 bool IsMainThread();
143
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100144#if RTC_DCHECK_IS_ON
Artem Titov96e3b992021-07-26 16:03:14 +0200145 // Registers that a Send operation is to be performed between `source` and
146 // `target`, while checking that this does not cause a send cycle that could
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100147 // potentially cause a deadlock.
148 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
149#endif
150
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151 private:
152 ThreadManager();
153 ~ThreadManager();
154
Byoungchan Lee14af7622022-01-12 05:24:58 +0900155 ThreadManager(const ThreadManager&) = delete;
156 ThreadManager& operator=(const ThreadManager&) = delete;
157
Sebastian Jansson178a6852020-01-14 11:12:26 +0100158 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100159 void AddInternal(Thread* message_queue);
160 void RemoveInternal(Thread* message_queue);
161 void ClearInternal(MessageHandler* handler);
162 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100163#if RTC_DCHECK_IS_ON
164 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
165#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100166
167 // This list contains all live Threads.
168 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
169
170 // Methods that don't modify the list of message queues may be called in a
171 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
172 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200173 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100174 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100175#if RTC_DCHECK_IS_ON
176 // Represents all thread seand actions by storing all send targets per thread.
177 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
178 // since we will trigger a CHECK failure if a cycle is introduced.
179 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
180#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100181
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200182#if defined(WEBRTC_POSIX)
183 pthread_key_t key_;
184#endif
185
186#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100187 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200188#endif
189
Niels Moller9d1840c2019-05-21 07:26:37 +0000190 // The thread to potentially autowrap.
191 const PlatformThreadRef main_thread_ref_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200192};
193
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200194// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
195
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100196class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700197 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100198 static const int kForever = -1;
199
200 // Create a new Thread and optionally assign it to the passed
201 // SocketServer. Subclasses that override Clear should pass false for
202 // init_queue and call DoInit() from their constructor to prevent races
203 // with the ThreadManager using the object while the vtable is still
204 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200205 explicit Thread(SocketServer* ss);
206 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100207
Taylor Brandstetter08672602018-03-02 15:20:33 -0800208 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200209 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800210 // instantiated class, which avoids a vptr data race.
211 Thread(SocketServer* ss, bool do_init);
212 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200213
214 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
215 // guarantee Stop() is explicitly called before the subclass is destroyed).
216 // This is required to avoid a data race between the destructor modifying the
217 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100218
219 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
220 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
221 // between the destructor modifying the vtable, and the ThreadManager
222 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200223 ~Thread() override;
224
Byoungchan Lee14af7622022-01-12 05:24:58 +0900225 Thread(const Thread&) = delete;
226 Thread& operator=(const Thread&) = delete;
227
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200228 static std::unique_ptr<Thread> CreateWithSocketServer();
229 static std::unique_ptr<Thread> Create();
230 static Thread* Current();
231
232 // Used to catch performance regressions. Use this to disallow blocking calls
233 // (Invoke) for a given scope. If a synchronous call is made while this is in
234 // effect, an assert will be triggered.
235 // Note that this is a single threaded class.
236 class ScopedDisallowBlockingCalls {
237 public:
238 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100239 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
240 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
241 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200242 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200243
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200244 private:
245 Thread* const thread_;
246 const bool previous_state_;
247 };
248
Tommife041642021-04-07 10:08:28 +0200249#if RTC_DCHECK_IS_ON
250 class ScopedCountBlockingCalls {
251 public:
252 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
253 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
254 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
255 delete;
256 ~ScopedCountBlockingCalls();
257
258 uint32_t GetBlockingCallCount() const;
259 uint32_t GetCouldBeBlockingCallCount() const;
260 uint32_t GetTotalBlockedCallCount() const;
261
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200262 void set_minimum_call_count_for_callback(uint32_t minimum) {
263 min_blocking_calls_for_callback_ = minimum;
264 }
265
Tommife041642021-04-07 10:08:28 +0200266 private:
267 Thread* const thread_;
268 const uint32_t base_blocking_call_count_;
269 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200270 // The minimum number of blocking calls required in order to issue the
271 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
272 // tame log spam.
273 // By default we always issue the callback, regardless of callback count.
274 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200275 std::function<void(uint32_t, uint32_t)> result_callback_;
276 };
277
278 uint32_t GetBlockingCallCount() const;
279 uint32_t GetCouldBeBlockingCallCount() const;
280#endif
281
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100282 SocketServer* socketserver();
283
284 // Note: The behavior of Thread has changed. When a thread is stopped,
285 // futher Posts and Sends will fail. However, any pending Sends and *ready*
286 // Posts (as opposed to unexpired delayed Posts) will be delivered before
287 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
288 // we eliminate the race condition when an MessageHandler and Thread
289 // may be destroyed independently of each other.
290 virtual void Quit();
291 virtual bool IsQuitting();
292 virtual void Restart();
293 // Not all message queues actually process messages (such as SignalThread).
294 // In those cases, it's important to know, before posting, that it won't be
295 // Processed. Normally, this would be true until IsQuitting() is true.
296 virtual bool IsProcessingMessagesForTesting();
297
298 // Get() will process I/O until:
299 // 1) A message is available (returns true)
300 // 2) cmsWait seconds have elapsed (returns false)
301 // 3) Stop() is called (returns false)
302 virtual bool Get(Message* pmsg,
303 int cmsWait = kForever,
304 bool process_io = true);
305 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Artem Titov96e3b992021-07-26 16:03:14 +0200306 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100307 virtual void Post(const Location& posted_from,
308 MessageHandler* phandler,
309 uint32_t id = 0,
310 MessageData* pdata = nullptr,
311 bool time_sensitive = false);
312 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100313 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100314 MessageHandler* phandler,
315 uint32_t id = 0,
316 MessageData* pdata = nullptr);
317 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100318 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100319 MessageHandler* phandler,
320 uint32_t id = 0,
321 MessageData* pdata = nullptr);
322 virtual void Clear(MessageHandler* phandler,
323 uint32_t id = MQID_ANY,
324 MessageList* removed = nullptr);
325 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100326
327 // Amount of time until the next message can be retrieved
328 virtual int GetDelay();
329
330 bool empty() const { return size() == 0u; }
331 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100332 CritScope cs(&crit_);
333 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100334 }
335
336 // Internally posts a message which causes the doomed object to be deleted
337 template <class T>
338 void Dispose(T* doomed) {
339 if (doomed) {
340 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
341 }
342 }
343
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200344 bool IsCurrent() const;
345
346 // Sleeps the calling thread for the specified number of milliseconds, during
347 // which time no processing is performed. Returns false if sleeping was
348 // interrupted by a signal (POSIX only).
349 static bool SleepMs(int millis);
350
351 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200352 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200353 const std::string& name() const { return name_; }
354 bool SetName(const std::string& name, const void* obj);
355
Harald Alvestrandba694422021-01-27 21:52:14 +0000356 // Sets the expected processing time in ms. The thread will write
357 // log messages when Invoke() takes more time than this.
358 // Default is 50 ms.
359 void SetDispatchWarningMs(int deadline);
360
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200361 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200362 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200363
364 // Tells the thread to stop and waits until it is joined.
365 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100366 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200367 // underlying OS thread.
368 virtual void Stop();
369
370 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
371 // work, override Run(). To receive and dispatch messages, call
372 // ProcessMessages occasionally.
373 virtual void Run();
374
375 virtual void Send(const Location& posted_from,
376 MessageHandler* phandler,
377 uint32_t id = 0,
378 MessageData* pdata = nullptr);
379
380 // Convenience method to invoke a functor on another thread. Caller must
Artem Titov96e3b992021-07-26 16:03:14 +0200381 // provide the `ReturnT` template argument, which cannot (easily) be deduced.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200382 // Uses Send() internally, which blocks the current thread until execution
383 // is complete.
384 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
385 // &MyFunctionReturningBool);
386 // NOTE: This function can only be called when synchronous calls are allowed.
387 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100388 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
389 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100390 template <
391 class ReturnT,
392 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
393 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
394 ReturnT result;
395 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
396 return result;
397 }
398
399 template <
400 class ReturnT,
401 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
402 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
403 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200404 }
405
Artem Titov96e3b992021-07-26 16:03:14 +0200406 // Allows invoke to specified `thread`. Thread never will be dereferenced and
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200407 // will be used only for reference-based comparison, so instance can be safely
Mirko Bonadei481e3452021-07-30 13:57:25 +0200408 // deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200409 // nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200410 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200411
Mirko Bonadei481e3452021-07-30 13:57:25 +0200412 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200413 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200414 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200415 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
416 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200417 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200418 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200419 bool IsInvokeToThreadAllowed(rtc::Thread* target);
420
Artem Titov96e3b992021-07-26 16:03:14 +0200421 // Posts a task to invoke the functor on `this` thread asynchronously, i.e.
422 // without blocking the thread that invoked PostTask(). Ownership of `functor`
423 // is passed and (usually, see below) destroyed on `this` thread after it is
Niels Möllerf13a0962019-05-17 10:15:06 +0200424 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100425 // Requirements of FunctorT:
426 // - FunctorT is movable.
427 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
Artem Titov96e3b992021-07-26 16:03:14 +0200428 // (if T is not void, the return value is discarded on `this` thread).
429 // - FunctorT has a public destructor that can be invoked from `this` thread
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100430 // after operation() has been invoked.
431 // - The functor must not cause the thread to quit before PostTask() is done.
432 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200433 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
Artem Titov96e3b992021-07-26 16:03:14 +0200434 // the task is run, it will be destroyed on `this` thread. However, if there
Niels Möllerf13a0962019-05-17 10:15:06 +0200435 // are pending tasks by the time the Thread is destroyed, or a task is posted
436 // to a thread that is quitting, the task is destroyed immediately, on the
437 // calling thread. Destroying the Thread only blocks for any currently running
438 // task to complete. Note that TQ abstraction is even vaguer on how
439 // destruction happens in these cases, allowing destruction to happen
440 // asynchronously at a later time and on some arbitrary thread. So to ease
441 // migration, don't depend on Thread::PostTask destroying un-run tasks
442 // immediately.
443 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100444 // Example - Calling a class method:
445 // class Foo {
446 // public:
447 // void DoTheThing();
448 // };
449 // Foo foo;
450 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
451 //
452 // Example - Calling a lambda function:
453 // thread->PostTask(RTC_FROM_HERE,
454 // [&x, &y] { x.TrackComputations(y.Compute()); });
Henrik Boströmcf9899c2022-01-20 09:46:16 +0100455 //
456 // TODO(https://crbug.com/webrtc/13582): Deprecate and remove in favor of the
457 // PostTask() method inherited from TaskQueueBase. Stop using it inside
458 // third_party/webrtc and add ABSL_DEPRECATED("bugs.webrtc.org/13582").
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100459 template <class FunctorT>
460 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800461 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200462 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100463 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100464 }
Henrik Boströmcf9899c2022-01-20 09:46:16 +0100465 // TODO(https://crbug.com/webrtc/13582): Deprecate and remove in favor of the
466 // PostTask() method inherited from TaskQueueBase. Stop using it inside
467 // third_party/webrtc and add ABSL_DEPRECATED("bugs.webrtc.org/13582").
Steve Antonbcc1a762019-12-11 11:21:53 -0800468 template <class FunctorT>
469 void PostDelayedTask(const Location& posted_from,
470 FunctorT&& functor,
471 uint32_t milliseconds) {
472 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
473 /*id=*/0,
474 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
475 std::forward<FunctorT>(functor)));
476 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100477
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100478 // From TaskQueueBase
479 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
480 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
481 uint32_t milliseconds) override;
Henrik Boströmcf9899c2022-01-20 09:46:16 +0100482 void PostDelayedHighPrecisionTask(std::unique_ptr<webrtc::QueuedTask> task,
483 uint32_t milliseconds) override;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100484 void Delete() override;
485
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200486 // ProcessMessages will process I/O and dispatch messages until:
487 // 1) cms milliseconds have elapsed (returns true)
488 // 2) Stop() is called (returns false)
489 bool ProcessMessages(int cms);
490
491 // Returns true if this is a thread that we created using the standard
492 // constructor, false if it was created by a call to
493 // ThreadManager::WrapCurrentThread(). The main thread of an application
494 // is generally not owned, since the OS representation of the thread
495 // obviously exists before we can get to it.
496 // You cannot call Start on non-owned threads.
497 bool IsOwned();
498
Tommi51492422017-12-04 15:18:23 +0100499 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200500 //
501 // DANGER: this is a terrible public API. Most callers that might want to
502 // call this likely do not have enough control/knowledge of the Thread in
503 // question to guarantee that the returned value remains true for the duration
504 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100505 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200507 // These functions are public to avoid injecting test hooks. Don't call them
508 // outside of tests.
509 // This method should be called when thread is created using non standard
510 // method, like derived implementation of rtc::Thread and it can not be
511 // started by calling Start(). This will set started flag to true and
512 // owned to false. This must be called from the current thread.
513 bool WrapCurrent();
514 void UnwrapCurrent();
515
Karl Wiberg32562252019-02-21 13:38:30 +0100516 // Sets the per-thread allow-blocking-calls flag to false; this is
517 // irrevocable. Must be called on this thread.
518 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
519
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200520 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100521 class CurrentThreadSetter : CurrentTaskQueueSetter {
522 public:
523 explicit CurrentThreadSetter(Thread* thread)
524 : CurrentTaskQueueSetter(thread),
525 manager_(rtc::ThreadManager::Instance()),
526 previous_(manager_->CurrentThread()) {
527 manager_->ChangeCurrentThreadForTest(thread);
528 }
529 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
530
531 private:
532 rtc::ThreadManager* const manager_;
533 rtc::Thread* const previous_;
534 };
535
Sebastian Jansson61380c02020-01-17 14:46:08 +0100536 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
537 // with the same trigger time are processed in num_ (FIFO) order.
538 class DelayedMessage {
539 public:
540 DelayedMessage(int64_t delay,
541 int64_t run_time_ms,
542 uint32_t num,
543 const Message& msg)
544 : delay_ms_(delay),
545 run_time_ms_(run_time_ms),
546 message_number_(num),
547 msg_(msg) {}
548
549 bool operator<(const DelayedMessage& dmsg) const {
550 return (dmsg.run_time_ms_ < run_time_ms_) ||
551 ((dmsg.run_time_ms_ == run_time_ms_) &&
552 (dmsg.message_number_ < message_number_));
553 }
554
555 int64_t delay_ms_; // for debugging
556 int64_t run_time_ms_;
557 // Monotonicaly incrementing number used for ordering of messages
558 // targeted to execute at the same time.
559 uint32_t message_number_;
560 Message msg_;
561 };
562
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100563 class PriorityQueue : public std::priority_queue<DelayedMessage> {
564 public:
565 container_type& container() { return c; }
566 void reheap() { make_heap(c.begin(), c.end(), comp); }
567 };
568
569 void DoDelayPost(const Location& posted_from,
570 int64_t cmsDelay,
571 int64_t tstamp,
572 MessageHandler* phandler,
573 uint32_t id,
574 MessageData* pdata);
575
576 // Perform initialization, subclasses must call this from their constructor
577 // if false was passed as init_queue to the Thread constructor.
578 void DoInit();
579
580 // Does not take any lock. Must be called either while holding crit_, or by
581 // the destructor (by definition, the latter has exclusive access).
582 void ClearInternal(MessageHandler* phandler,
583 uint32_t id,
584 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
585
586 // Perform cleanup; subclasses must call this from the destructor,
587 // and are not expected to actually hold the lock.
588 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
589
590 void WakeUpSocketServer();
591
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200592 // Same as WrapCurrent except that it never fails as it does not try to
593 // acquire the synchronization access of the thread. The caller should never
594 // call Stop() or Join() on this thread.
595 void SafeWrapCurrent();
596
597 // Blocks the calling thread until this thread has terminated.
598 void Join();
599
600 static void AssertBlockingIsAllowedOnCurrentThread();
601
602 friend class ScopedDisallowBlockingCalls;
603
Markus Handell3cb525b2020-07-16 16:16:09 +0200604 RecursiveCriticalSection* CritForTest() { return &crit_; }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100605
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200606 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000607 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
608
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100609 class QueuedTaskHandler final : public MessageHandler {
610 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200611 QueuedTaskHandler() {}
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100612 void OnMessage(Message* msg) override;
613 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800614
Karl Wiberg32562252019-02-21 13:38:30 +0100615 // Sets the per-thread allow-blocking-calls flag and returns the previous
616 // value. Must be called on this thread.
617 bool SetAllowBlockingCalls(bool allow);
618
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200619#if defined(WEBRTC_WIN)
620 static DWORD WINAPI PreRun(LPVOID context);
621#else
Yves Gerey665174f2018-06-19 15:03:05 +0200622 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200623#endif
624
625 // ThreadManager calls this instead WrapCurrent() because
626 // ThreadManager::Instance() cannot be used while ThreadManager is
627 // being created.
628 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200629 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200630 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
631 bool need_synchronize_access);
632
Tommi51492422017-12-04 15:18:23 +0100633 // Return true if the thread is currently running.
634 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200635
Danil Chapovalov89313452019-11-29 12:56:43 +0100636 void InvokeInternal(const Location& posted_from,
637 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200638
Tommi6866dc72020-05-15 10:11:56 +0200639 // Called by the ThreadManager when being set as the current thread.
640 void EnsureIsCurrentTaskQueue();
641
642 // Called by the ThreadManager when being unset as the current thread.
643 void ClearCurrentTaskQueue();
644
Steve Antonbcc1a762019-12-11 11:21:53 -0800645 // Returns a static-lifetime MessageHandler which runs message with
646 // MessageLikeTask payload data.
647 static MessageHandler* GetPostTaskMessageHandler();
648
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100649 bool fPeekKeep_;
650 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100651 MessageList messages_ RTC_GUARDED_BY(crit_);
652 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
653 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200654#if RTC_DCHECK_IS_ON
655 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
656 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200657 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
658 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
659#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200660 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100661 bool fInitialized_;
662 bool fDestroyed_;
663
664 volatile int stop_;
665
666 // The SocketServer might not be owned by Thread.
667 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200668 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100669 std::unique_ptr<SocketServer> own_ss_;
670
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200671 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100672
Jonas Olssona4d87372019-07-05 19:08:33 +0200673 // TODO(tommi): Add thread checks for proper use of control methods.
674 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200675
676#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100677 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200678#endif
679
680#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100681 HANDLE thread_ = nullptr;
682 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200683#endif
684
Tommi51492422017-12-04 15:18:23 +0100685 // Indicates whether or not ownership of the worker thread lies with
686 // this instance or not. (i.e. owned_ == !wrapped).
687 // Must only be modified when the worker thread is not running.
688 bool owned_ = true;
689
690 // Only touched from the worker thread itself.
691 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200692
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100693 // Runs webrtc::QueuedTask posted to the Thread.
694 QueuedTaskHandler queued_task_handler_;
Tommi6866dc72020-05-15 10:11:56 +0200695 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
696 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100697
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200698 friend class ThreadManager;
699
Harald Alvestrandba694422021-01-27 21:52:14 +0000700 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200701};
702
703// AutoThread automatically installs itself at construction
704// uninstalls at destruction, if a Thread object is
705// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200706//
707// NOTE: *** This class should only be used by tests ***
708//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200709class AutoThread : public Thread {
710 public:
711 AutoThread();
712 ~AutoThread() override;
713
Byoungchan Lee14af7622022-01-12 05:24:58 +0900714 AutoThread(const AutoThread&) = delete;
715 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200716};
717
718// AutoSocketServerThread automatically installs itself at
719// construction and uninstalls at destruction. If a Thread object is
720// already associated with the current OS thread, it is temporarily
721// disassociated and restored by the destructor.
722
723class AutoSocketServerThread : public Thread {
724 public:
725 explicit AutoSocketServerThread(SocketServer* ss);
726 ~AutoSocketServerThread() override;
727
Byoungchan Lee14af7622022-01-12 05:24:58 +0900728 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
729 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
730
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200731 private:
732 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200733};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200734} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000735
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200736#endif // RTC_BASE_THREAD_H_