blob: 3c4ed558cd13a5cc4be8e1c2fda8969dd250fb2d [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
Henrik Boström2deee4b2022-01-20 11:58:05 +010028#include "absl/base/attributes.h"
Danil Chapovalov89313452019-11-29 12:56:43 +010029#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010030#include "api/task_queue/queued_task.h"
31#include "api/task_queue/task_queue_base.h"
Mirko Bonadei481e3452021-07-30 13:57:25 +020032#include "rtc_base/checks.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020033#include "rtc_base/deprecated/recursive_critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020038#include "rtc_base/system/rtc_export.h"
Henrik Boström2deee4b2022-01-20 11:58:05 +010039#include "rtc_base/task_utils/to_queued_task.h"
Yves Gerey988cc082018-10-23 12:03:01 +020040#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010041#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020042
43#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020045#endif
46
Tommife041642021-04-07 10:08:28 +020047#if RTC_DCHECK_IS_ON
48// Counts how many blocking Thread::Invoke or Thread::Send calls are made from
49// within a scope and logs the number of blocking calls at the end of the scope.
50#define RTC_LOG_THREAD_BLOCK_COUNT() \
51 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
52 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
53 auto total = actual_block + could_block; \
54 if (total) { \
55 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
56 << " (actual=" << actual_block \
57 << ", could=" << could_block << ")"; \
58 } \
59 })
60
61// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
62// less than or equal to a specific value. Use to avoid regressing in the
63// number of blocking thread calls.
64// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
65// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020066#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
67 do { \
68 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
69 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
70 } while (0)
Tommife041642021-04-07 10:08:28 +020071#else
72#define RTC_LOG_THREAD_BLOCK_COUNT()
73#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
74#endif
75
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020076namespace rtc {
77
78class Thread;
79
Henrik Boströmba4dcc32019-02-28 09:34:06 +010080namespace rtc_thread_internal {
81
Niels Möllerf13a0962019-05-17 10:15:06 +020082class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010083 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020084 virtual void Run() = 0;
85};
86
87template <class FunctorT>
88class MessageWithFunctor final : public MessageLikeTask {
89 public:
90 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010091 : functor_(std::forward<FunctorT>(functor)) {}
92
Byoungchan Lee14af7622022-01-12 05:24:58 +090093 MessageWithFunctor(const MessageWithFunctor&) = delete;
94 MessageWithFunctor& operator=(const MessageWithFunctor&) = delete;
95
Niels Möllerf13a0962019-05-17 10:15:06 +020096 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010097
98 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020099 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100100
101 typename std::remove_reference<FunctorT>::type functor_;
Niels Möllerf13a0962019-05-17 10:15:06 +0200102};
103
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100104} // namespace rtc_thread_internal
105
Mirko Bonadei35214fc2019-09-23 14:54:28 +0200106class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200107 public:
108 static const int kForever = -1;
109
110 // Singleton, constructor and destructor are private.
111 static ThreadManager* Instance();
112
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100113 static void Add(Thread* message_queue);
114 static void Remove(Thread* message_queue);
115 static void Clear(MessageHandler* handler);
116
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100117 // For testing purposes, for use with a simulated clock.
118 // Ensures that all message queues have processed delayed messages
119 // up until the current point in time.
120 static void ProcessAllMessageQueuesForTesting();
121
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 Thread* CurrentThread();
123 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +0100124 // Allows changing the current thread, this is intended for tests where we
125 // want to simulate multiple threads running on a single physical thread.
126 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127
128 // Returns a thread object with its thread_ ivar set
129 // to whatever the OS uses to represent the thread.
130 // If there already *is* a Thread object corresponding to this thread,
131 // this method will return that. Otherwise it creates a new Thread
132 // object whose wrapped() method will return true, and whose
133 // handle will, on Win32, be opened with only synchronization privileges -
134 // if you need more privilegs, rather than changing this method, please
135 // write additional code to adjust the privileges, or call a different
136 // factory method of your own devising, because this one gets used in
137 // unexpected contexts (like inside browser plugins) and it would be a
138 // shame to break it. It is also conceivable on Win32 that we won't even
139 // be able to get synchronization privileges, in which case the result
140 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200141 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200142 void UnwrapCurrentThread();
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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200189};
190
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
192
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100193class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700194 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100195 static const int kForever = -1;
196
197 // Create a new Thread and optionally assign it to the passed
198 // SocketServer. Subclasses that override Clear should pass false for
199 // init_queue and call DoInit() from their constructor to prevent races
200 // with the ThreadManager using the object while the vtable is still
201 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200202 explicit Thread(SocketServer* ss);
203 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100204
Taylor Brandstetter08672602018-03-02 15:20:33 -0800205 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200206 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800207 // instantiated class, which avoids a vptr data race.
208 Thread(SocketServer* ss, bool do_init);
209 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200210
211 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
212 // guarantee Stop() is explicitly called before the subclass is destroyed).
213 // This is required to avoid a data race between the destructor modifying the
214 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100215
216 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
217 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
218 // between the destructor modifying the vtable, and the ThreadManager
219 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200220 ~Thread() override;
221
Byoungchan Lee14af7622022-01-12 05:24:58 +0900222 Thread(const Thread&) = delete;
223 Thread& operator=(const Thread&) = delete;
224
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200225 static std::unique_ptr<Thread> CreateWithSocketServer();
226 static std::unique_ptr<Thread> Create();
227 static Thread* Current();
228
229 // Used to catch performance regressions. Use this to disallow blocking calls
230 // (Invoke) for a given scope. If a synchronous call is made while this is in
231 // effect, an assert will be triggered.
232 // Note that this is a single threaded class.
233 class ScopedDisallowBlockingCalls {
234 public:
235 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100236 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
237 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
238 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200239 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200240
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200241 private:
242 Thread* const thread_;
243 const bool previous_state_;
244 };
245
Tommife041642021-04-07 10:08:28 +0200246#if RTC_DCHECK_IS_ON
247 class ScopedCountBlockingCalls {
248 public:
249 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
250 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
251 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
252 delete;
253 ~ScopedCountBlockingCalls();
254
255 uint32_t GetBlockingCallCount() const;
256 uint32_t GetCouldBeBlockingCallCount() const;
257 uint32_t GetTotalBlockedCallCount() const;
258
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200259 void set_minimum_call_count_for_callback(uint32_t minimum) {
260 min_blocking_calls_for_callback_ = minimum;
261 }
262
Tommife041642021-04-07 10:08:28 +0200263 private:
264 Thread* const thread_;
265 const uint32_t base_blocking_call_count_;
266 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200267 // The minimum number of blocking calls required in order to issue the
268 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
269 // tame log spam.
270 // By default we always issue the callback, regardless of callback count.
271 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200272 std::function<void(uint32_t, uint32_t)> result_callback_;
273 };
274
275 uint32_t GetBlockingCallCount() const;
276 uint32_t GetCouldBeBlockingCallCount() const;
277#endif
278
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100279 SocketServer* socketserver();
280
281 // Note: The behavior of Thread has changed. When a thread is stopped,
282 // futher Posts and Sends will fail. However, any pending Sends and *ready*
283 // Posts (as opposed to unexpired delayed Posts) will be delivered before
284 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
285 // we eliminate the race condition when an MessageHandler and Thread
286 // may be destroyed independently of each other.
287 virtual void Quit();
288 virtual bool IsQuitting();
289 virtual void Restart();
290 // Not all message queues actually process messages (such as SignalThread).
291 // In those cases, it's important to know, before posting, that it won't be
292 // Processed. Normally, this would be true until IsQuitting() is true.
293 virtual bool IsProcessingMessagesForTesting();
294
295 // Get() will process I/O until:
296 // 1) A message is available (returns true)
297 // 2) cmsWait seconds have elapsed (returns false)
298 // 3) Stop() is called (returns false)
299 virtual bool Get(Message* pmsg,
300 int cmsWait = kForever,
301 bool process_io = true);
302 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Artem Titov96e3b992021-07-26 16:03:14 +0200303 // `time_sensitive` is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100304 virtual void Post(const Location& posted_from,
305 MessageHandler* phandler,
306 uint32_t id = 0,
307 MessageData* pdata = nullptr,
308 bool time_sensitive = false);
309 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100310 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100311 MessageHandler* phandler,
312 uint32_t id = 0,
313 MessageData* pdata = nullptr);
314 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100315 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100316 MessageHandler* phandler,
317 uint32_t id = 0,
318 MessageData* pdata = nullptr);
319 virtual void Clear(MessageHandler* phandler,
320 uint32_t id = MQID_ANY,
321 MessageList* removed = nullptr);
322 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100323
324 // Amount of time until the next message can be retrieved
325 virtual int GetDelay();
326
327 bool empty() const { return size() == 0u; }
328 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100329 CritScope cs(&crit_);
330 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100331 }
332
333 // Internally posts a message which causes the doomed object to be deleted
334 template <class T>
335 void Dispose(T* doomed) {
336 if (doomed) {
337 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
338 }
339 }
340
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200341 bool IsCurrent() const;
342
343 // Sleeps the calling thread for the specified number of milliseconds, during
344 // which time no processing is performed. Returns false if sleeping was
345 // interrupted by a signal (POSIX only).
346 static bool SleepMs(int millis);
347
348 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200349 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200350 const std::string& name() const { return name_; }
351 bool SetName(const std::string& name, const void* obj);
352
Harald Alvestrandba694422021-01-27 21:52:14 +0000353 // Sets the expected processing time in ms. The thread will write
354 // log messages when Invoke() takes more time than this.
355 // Default is 50 ms.
356 void SetDispatchWarningMs(int deadline);
357
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200358 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200359 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200360
361 // Tells the thread to stop and waits until it is joined.
362 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100363 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200364 // underlying OS thread.
365 virtual void Stop();
366
367 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
368 // work, override Run(). To receive and dispatch messages, call
369 // ProcessMessages occasionally.
370 virtual void Run();
371
372 virtual void Send(const Location& posted_from,
373 MessageHandler* phandler,
374 uint32_t id = 0,
375 MessageData* pdata = nullptr);
376
377 // Convenience method to invoke a functor on another thread. Caller must
Artem Titov96e3b992021-07-26 16:03:14 +0200378 // provide the `ReturnT` template argument, which cannot (easily) be deduced.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200379 // Uses Send() internally, which blocks the current thread until execution
380 // is complete.
381 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
382 // &MyFunctionReturningBool);
383 // NOTE: This function can only be called when synchronous calls are allowed.
384 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100385 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
386 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100387 template <
388 class ReturnT,
389 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
390 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
391 ReturnT result;
392 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
393 return result;
394 }
395
396 template <
397 class ReturnT,
398 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
399 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
400 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200401 }
402
Artem Titov96e3b992021-07-26 16:03:14 +0200403 // Allows invoke to specified `thread`. Thread never will be dereferenced and
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200404 // will be used only for reference-based comparison, so instance can be safely
Mirko Bonadei481e3452021-07-30 13:57:25 +0200405 // deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200406 // nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200407 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200408
Mirko Bonadei481e3452021-07-30 13:57:25 +0200409 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200410 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200411 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200412 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
413 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200414 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200415 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200416 bool IsInvokeToThreadAllowed(rtc::Thread* target);
417
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100418 // From TaskQueueBase
419 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
420 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
421 uint32_t milliseconds) override;
Henrik Boströmcf9899c2022-01-20 09:46:16 +0100422 void PostDelayedHighPrecisionTask(std::unique_ptr<webrtc::QueuedTask> task,
423 uint32_t milliseconds) override;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100424 void Delete() override;
425
Henrik Boström2deee4b2022-01-20 11:58:05 +0100426 // Helper methods to avoid having to do ToQueuedTask() at the calling places.
427 template <class Closure,
428 typename std::enable_if<!std::is_convertible<
429 Closure,
430 std::unique_ptr<webrtc::QueuedTask>>::value>::type* = nullptr>
431 void PostTask(Closure&& closure) {
432 PostTask(webrtc::ToQueuedTask(std::forward<Closure>(closure)));
433 }
434 template <class Closure,
435 typename std::enable_if<!std::is_convertible<
436 Closure,
437 std::unique_ptr<webrtc::QueuedTask>>::value>::type* = nullptr>
438 void PostDelayedTask(Closure&& closure, uint32_t milliseconds) {
439 PostDelayedTask(webrtc::ToQueuedTask(std::forward<Closure>(closure)),
440 milliseconds);
441 }
442 template <class Closure,
443 typename std::enable_if<!std::is_convertible<
444 Closure,
445 std::unique_ptr<webrtc::QueuedTask>>::value>::type* = nullptr>
446 void PostDelayedHighPrecisionTask(Closure&& closure, uint32_t milliseconds) {
447 PostDelayedHighPrecisionTask(
448 webrtc::ToQueuedTask(std::forward<Closure>(closure)), milliseconds);
449 }
450
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200451 // ProcessMessages will process I/O and dispatch messages until:
452 // 1) cms milliseconds have elapsed (returns true)
453 // 2) Stop() is called (returns false)
454 bool ProcessMessages(int cms);
455
456 // Returns true if this is a thread that we created using the standard
457 // constructor, false if it was created by a call to
458 // ThreadManager::WrapCurrentThread(). The main thread of an application
459 // is generally not owned, since the OS representation of the thread
460 // obviously exists before we can get to it.
461 // You cannot call Start on non-owned threads.
462 bool IsOwned();
463
Tommi51492422017-12-04 15:18:23 +0100464 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200465 //
466 // DANGER: this is a terrible public API. Most callers that might want to
467 // call this likely do not have enough control/knowledge of the Thread in
468 // question to guarantee that the returned value remains true for the duration
469 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100470 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200471
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200472 // These functions are public to avoid injecting test hooks. Don't call them
473 // outside of tests.
474 // This method should be called when thread is created using non standard
475 // method, like derived implementation of rtc::Thread and it can not be
476 // started by calling Start(). This will set started flag to true and
477 // owned to false. This must be called from the current thread.
478 bool WrapCurrent();
479 void UnwrapCurrent();
480
Karl Wiberg32562252019-02-21 13:38:30 +0100481 // Sets the per-thread allow-blocking-calls flag to false; this is
482 // irrevocable. Must be called on this thread.
483 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
484
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200485 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100486 class CurrentThreadSetter : CurrentTaskQueueSetter {
487 public:
488 explicit CurrentThreadSetter(Thread* thread)
489 : CurrentTaskQueueSetter(thread),
490 manager_(rtc::ThreadManager::Instance()),
491 previous_(manager_->CurrentThread()) {
492 manager_->ChangeCurrentThreadForTest(thread);
493 }
494 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
495
496 private:
497 rtc::ThreadManager* const manager_;
498 rtc::Thread* const previous_;
499 };
500
Sebastian Jansson61380c02020-01-17 14:46:08 +0100501 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
502 // with the same trigger time are processed in num_ (FIFO) order.
503 class DelayedMessage {
504 public:
505 DelayedMessage(int64_t delay,
506 int64_t run_time_ms,
507 uint32_t num,
508 const Message& msg)
509 : delay_ms_(delay),
510 run_time_ms_(run_time_ms),
511 message_number_(num),
512 msg_(msg) {}
513
514 bool operator<(const DelayedMessage& dmsg) const {
515 return (dmsg.run_time_ms_ < run_time_ms_) ||
516 ((dmsg.run_time_ms_ == run_time_ms_) &&
517 (dmsg.message_number_ < message_number_));
518 }
519
520 int64_t delay_ms_; // for debugging
521 int64_t run_time_ms_;
522 // Monotonicaly incrementing number used for ordering of messages
523 // targeted to execute at the same time.
524 uint32_t message_number_;
525 Message msg_;
526 };
527
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100528 class PriorityQueue : public std::priority_queue<DelayedMessage> {
529 public:
530 container_type& container() { return c; }
531 void reheap() { make_heap(c.begin(), c.end(), comp); }
532 };
533
534 void DoDelayPost(const Location& posted_from,
535 int64_t cmsDelay,
536 int64_t tstamp,
537 MessageHandler* phandler,
538 uint32_t id,
539 MessageData* pdata);
540
541 // Perform initialization, subclasses must call this from their constructor
542 // if false was passed as init_queue to the Thread constructor.
543 void DoInit();
544
545 // Does not take any lock. Must be called either while holding crit_, or by
546 // the destructor (by definition, the latter has exclusive access).
547 void ClearInternal(MessageHandler* phandler,
548 uint32_t id,
549 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
550
551 // Perform cleanup; subclasses must call this from the destructor,
552 // and are not expected to actually hold the lock.
553 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
554
555 void WakeUpSocketServer();
556
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200557 // Same as WrapCurrent except that it never fails as it does not try to
558 // acquire the synchronization access of the thread. The caller should never
559 // call Stop() or Join() on this thread.
560 void SafeWrapCurrent();
561
562 // Blocks the calling thread until this thread has terminated.
563 void Join();
564
565 static void AssertBlockingIsAllowedOnCurrentThread();
566
567 friend class ScopedDisallowBlockingCalls;
568
Markus Handell3cb525b2020-07-16 16:16:09 +0200569 RecursiveCriticalSection* CritForTest() { return &crit_; }
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100570
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200571 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000572 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
573
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100574 class QueuedTaskHandler final : public MessageHandler {
575 public:
Tomas Gunnarsson77baeee2020-09-24 22:39:21 +0200576 QueuedTaskHandler() {}
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100577 void OnMessage(Message* msg) override;
578 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800579
Karl Wiberg32562252019-02-21 13:38:30 +0100580 // Sets the per-thread allow-blocking-calls flag and returns the previous
581 // value. Must be called on this thread.
582 bool SetAllowBlockingCalls(bool allow);
583
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200584#if defined(WEBRTC_WIN)
585 static DWORD WINAPI PreRun(LPVOID context);
586#else
Yves Gerey665174f2018-06-19 15:03:05 +0200587 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200588#endif
589
590 // ThreadManager calls this instead WrapCurrent() because
591 // ThreadManager::Instance() cannot be used while ThreadManager is
592 // being created.
593 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200594 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200595 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
596 bool need_synchronize_access);
597
Tommi51492422017-12-04 15:18:23 +0100598 // Return true if the thread is currently running.
599 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200600
Danil Chapovalov89313452019-11-29 12:56:43 +0100601 void InvokeInternal(const Location& posted_from,
602 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200603
Tommi6866dc72020-05-15 10:11:56 +0200604 // Called by the ThreadManager when being set as the current thread.
605 void EnsureIsCurrentTaskQueue();
606
607 // Called by the ThreadManager when being unset as the current thread.
608 void ClearCurrentTaskQueue();
609
Steve Antonbcc1a762019-12-11 11:21:53 -0800610 // Returns a static-lifetime MessageHandler which runs message with
611 // MessageLikeTask payload data.
612 static MessageHandler* GetPostTaskMessageHandler();
613
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100614 bool fPeekKeep_;
615 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100616 MessageList messages_ RTC_GUARDED_BY(crit_);
617 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
618 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200619#if RTC_DCHECK_IS_ON
620 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
621 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200622 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
623 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
624#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200625 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100626 bool fInitialized_;
627 bool fDestroyed_;
628
629 volatile int stop_;
630
631 // The SocketServer might not be owned by Thread.
632 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200633 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100634 std::unique_ptr<SocketServer> own_ss_;
635
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200636 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100637
Jonas Olssona4d87372019-07-05 19:08:33 +0200638 // TODO(tommi): Add thread checks for proper use of control methods.
639 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200640
641#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100642 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200643#endif
644
645#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100646 HANDLE thread_ = nullptr;
647 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200648#endif
649
Tommi51492422017-12-04 15:18:23 +0100650 // Indicates whether or not ownership of the worker thread lies with
651 // this instance or not. (i.e. owned_ == !wrapped).
652 // Must only be modified when the worker thread is not running.
653 bool owned_ = true;
654
655 // Only touched from the worker thread itself.
656 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200657
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100658 // Runs webrtc::QueuedTask posted to the Thread.
659 QueuedTaskHandler queued_task_handler_;
Tommi6866dc72020-05-15 10:11:56 +0200660 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
661 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100662
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200663 friend class ThreadManager;
664
Harald Alvestrandba694422021-01-27 21:52:14 +0000665 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200666};
667
668// AutoThread automatically installs itself at construction
669// uninstalls at destruction, if a Thread object is
670// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200671//
672// NOTE: *** This class should only be used by tests ***
673//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200674class AutoThread : public Thread {
675 public:
676 AutoThread();
677 ~AutoThread() override;
678
Byoungchan Lee14af7622022-01-12 05:24:58 +0900679 AutoThread(const AutoThread&) = delete;
680 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200681};
682
683// AutoSocketServerThread automatically installs itself at
684// construction and uninstalls at destruction. If a Thread object is
685// already associated with the current OS thread, it is temporarily
686// disassociated and restored by the destructor.
687
688class AutoSocketServerThread : public Thread {
689 public:
690 explicit AutoSocketServerThread(SocketServer* ss);
691 ~AutoSocketServerThread() override;
692
Byoungchan Lee14af7622022-01-12 05:24:58 +0900693 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
694 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
695
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200696 private:
697 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200698};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200699} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000700
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200701#endif // RTC_BASE_THREAD_H_