blob: 3fa75330a54defe1e79347ab7533fde031961251 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020041#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020042#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043
44#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020046#endif
47
Tommife041642021-04-07 10:08:28 +020048#if RTC_DCHECK_IS_ON
Danil Chapovalov7c323ad2022-09-08 13:13:53 +020049// Counts how many `Thread::BlockingCall` are made from within a scope and logs
50// the number of blocking calls at the end of the scope.
Tommife041642021-04-07 10:08:28 +020051#define RTC_LOG_THREAD_BLOCK_COUNT() \
52 rtc::Thread::ScopedCountBlockingCalls blocked_call_count_printer( \
53 [func = __func__](uint32_t actual_block, uint32_t could_block) { \
54 auto total = actual_block + could_block; \
55 if (total) { \
56 RTC_LOG(LS_WARNING) << "Blocking " << func << ": total=" << total \
57 << " (actual=" << actual_block \
58 << ", could=" << could_block << ")"; \
59 } \
60 })
61
62// Adds an RTC_DCHECK_LE that checks that the number of blocking calls are
63// less than or equal to a specific value. Use to avoid regressing in the
64// number of blocking thread calls.
65// Note: Use of this macro, requires RTC_LOG_THREAD_BLOCK_COUNT() to be called
66// first.
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +020067#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x) \
68 do { \
69 blocked_call_count_printer.set_minimum_call_count_for_callback(x + 1); \
70 RTC_DCHECK_LE(blocked_call_count_printer.GetTotalBlockedCallCount(), x); \
71 } while (0)
Tommife041642021-04-07 10:08:28 +020072#else
73#define RTC_LOG_THREAD_BLOCK_COUNT()
74#define RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(x)
75#endif
76
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020077namespace rtc {
78
79class Thread;
80
Mirko Bonadei35214fc2019-09-23 14:54:28 +020081class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020082 public:
83 static const int kForever = -1;
84
85 // Singleton, constructor and destructor are private.
86 static ThreadManager* Instance();
87
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010088 static void Add(Thread* message_queue);
89 static void Remove(Thread* message_queue);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010090
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010091 // For testing purposes, for use with a simulated clock.
92 // Ensures that all message queues have processed delayed messages
93 // up until the current point in time.
94 static void ProcessAllMessageQueuesForTesting();
95
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020096 Thread* CurrentThread();
97 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +010098 // Allows changing the current thread, this is intended for tests where we
99 // want to simulate multiple threads running on a single physical thread.
100 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200101
102 // Returns a thread object with its thread_ ivar set
103 // to whatever the OS uses to represent the thread.
104 // If there already *is* a Thread object corresponding to this thread,
105 // this method will return that. Otherwise it creates a new Thread
106 // object whose wrapped() method will return true, and whose
107 // handle will, on Win32, be opened with only synchronization privileges -
108 // if you need more privilegs, rather than changing this method, please
109 // write additional code to adjust the privileges, or call a different
110 // factory method of your own devising, because this one gets used in
111 // unexpected contexts (like inside browser plugins) and it would be a
112 // shame to break it. It is also conceivable on Win32 that we won't even
113 // be able to get synchronization privileges, in which case the result
114 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200115 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200116 void UnwrapCurrentThread();
117
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100118#if RTC_DCHECK_IS_ON
Artem Titov96e3b992021-07-26 16:03:14 +0200119 // Registers that a Send operation is to be performed between `source` and
120 // `target`, while checking that this does not cause a send cycle that could
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100121 // potentially cause a deadlock.
122 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
123#endif
124
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200125 private:
126 ThreadManager();
127 ~ThreadManager();
128
Byoungchan Lee14af7622022-01-12 05:24:58 +0900129 ThreadManager(const ThreadManager&) = delete;
130 ThreadManager& operator=(const ThreadManager&) = delete;
131
Sebastian Jansson178a6852020-01-14 11:12:26 +0100132 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100133 void AddInternal(Thread* message_queue);
134 void RemoveInternal(Thread* message_queue);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100135 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100136#if RTC_DCHECK_IS_ON
137 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
138#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100139
140 // This list contains all live Threads.
141 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
142
143 // Methods that don't modify the list of message queues may be called in a
144 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
145 // calls.
Markus Handell3cb525b2020-07-16 16:16:09 +0200146 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100147 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100148#if RTC_DCHECK_IS_ON
149 // Represents all thread seand actions by storing all send targets per thread.
150 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
151 // since we will trigger a CHECK failure if a cycle is introduced.
152 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
153#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100154
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155#if defined(WEBRTC_POSIX)
156 pthread_key_t key_;
157#endif
158
159#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100160 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200161#endif
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200162};
163
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
165
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100166class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700167 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100168 static const int kForever = -1;
169
170 // Create a new Thread and optionally assign it to the passed
171 // SocketServer. Subclasses that override Clear should pass false for
172 // init_queue and call DoInit() from their constructor to prevent races
173 // with the ThreadManager using the object while the vtable is still
174 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200175 explicit Thread(SocketServer* ss);
176 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100177
Taylor Brandstetter08672602018-03-02 15:20:33 -0800178 // Constructors meant for subclasses; they should call DoInit themselves and
Artem Titov96e3b992021-07-26 16:03:14 +0200179 // pass false for `do_init`, so that DoInit is called only on the fully
Taylor Brandstetter08672602018-03-02 15:20:33 -0800180 // instantiated class, which avoids a vptr data race.
181 Thread(SocketServer* ss, bool do_init);
182 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200183
184 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
185 // guarantee Stop() is explicitly called before the subclass is destroyed).
186 // This is required to avoid a data race between the destructor modifying the
187 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100188
189 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
190 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
191 // between the destructor modifying the vtable, and the ThreadManager
192 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200193 ~Thread() override;
194
Byoungchan Lee14af7622022-01-12 05:24:58 +0900195 Thread(const Thread&) = delete;
196 Thread& operator=(const Thread&) = delete;
197
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 static std::unique_ptr<Thread> CreateWithSocketServer();
199 static std::unique_ptr<Thread> Create();
200 static Thread* Current();
201
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200202 // Used to catch performance regressions. Use this to disallow BlockingCall
203 // for a given scope. If a synchronous call is made while this is in
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200204 // effect, an assert will be triggered.
205 // Note that this is a single threaded class.
206 class ScopedDisallowBlockingCalls {
207 public:
208 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100209 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
210 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
211 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200212 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200213
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200214 private:
215 Thread* const thread_;
216 const bool previous_state_;
217 };
218
Tommife041642021-04-07 10:08:28 +0200219#if RTC_DCHECK_IS_ON
220 class ScopedCountBlockingCalls {
221 public:
222 ScopedCountBlockingCalls(std::function<void(uint32_t, uint32_t)> callback);
223 ScopedCountBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
224 ScopedCountBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
225 delete;
226 ~ScopedCountBlockingCalls();
227
228 uint32_t GetBlockingCallCount() const;
229 uint32_t GetCouldBeBlockingCallCount() const;
230 uint32_t GetTotalBlockedCallCount() const;
231
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200232 void set_minimum_call_count_for_callback(uint32_t minimum) {
233 min_blocking_calls_for_callback_ = minimum;
234 }
235
Tommife041642021-04-07 10:08:28 +0200236 private:
237 Thread* const thread_;
238 const uint32_t base_blocking_call_count_;
239 const uint32_t base_could_be_blocking_call_count_;
Tomas Gunnarsson89f3dd52021-04-14 12:54:10 +0200240 // The minimum number of blocking calls required in order to issue the
241 // result_callback_. This is used by RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN to
242 // tame log spam.
243 // By default we always issue the callback, regardless of callback count.
244 uint32_t min_blocking_calls_for_callback_ = 0;
Tommife041642021-04-07 10:08:28 +0200245 std::function<void(uint32_t, uint32_t)> result_callback_;
246 };
247
248 uint32_t GetBlockingCallCount() const;
249 uint32_t GetCouldBeBlockingCallCount() const;
250#endif
251
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100252 SocketServer* socketserver();
253
254 // Note: The behavior of Thread has changed. When a thread is stopped,
255 // futher Posts and Sends will fail. However, any pending Sends and *ready*
256 // Posts (as opposed to unexpired delayed Posts) will be delivered before
257 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
258 // we eliminate the race condition when an MessageHandler and Thread
259 // may be destroyed independently of each other.
260 virtual void Quit();
261 virtual bool IsQuitting();
262 virtual void Restart();
263 // Not all message queues actually process messages (such as SignalThread).
264 // In those cases, it's important to know, before posting, that it won't be
265 // Processed. Normally, this would be true until IsQuitting() is true.
266 virtual bool IsProcessingMessagesForTesting();
267
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100268 // Amount of time until the next message can be retrieved
269 virtual int GetDelay();
270
271 bool empty() const { return size() == 0u; }
272 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100273 CritScope cs(&crit_);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200274 return messages_.size() + delayed_messages_.size();
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100275 }
276
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200277 bool IsCurrent() const;
278
279 // Sleeps the calling thread for the specified number of milliseconds, during
280 // which time no processing is performed. Returns false if sleeping was
281 // interrupted by a signal (POSIX only).
282 static bool SleepMs(int millis);
283
284 // Sets the thread's name, for debugging. Must be called before Start().
Artem Titov96e3b992021-07-26 16:03:14 +0200285 // If `obj` is non-null, its value is appended to `name`.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200286 const std::string& name() const { return name_; }
Ali Tofigh7fa90572022-03-17 15:47:49 +0100287 bool SetName(absl::string_view name, const void* obj);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200288
Harald Alvestrandba694422021-01-27 21:52:14 +0000289 // Sets the expected processing time in ms. The thread will write
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200290 // log messages when Dispatch() takes more time than this.
Harald Alvestrandba694422021-01-27 21:52:14 +0000291 // Default is 50 ms.
292 void SetDispatchWarningMs(int deadline);
293
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200294 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200295 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200296
297 // Tells the thread to stop and waits until it is joined.
298 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100299 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200300 // underlying OS thread.
301 virtual void Stop();
302
303 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
304 // work, override Run(). To receive and dispatch messages, call
305 // ProcessMessages occasionally.
306 virtual void Run();
307
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200308 // Convenience method to invoke a functor on another thread.
309 // Blocks the current thread until execution is complete.
310 // Ex: thread.BlockingCall([&] { result = MyFunctionReturningBool(); });
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200311 // NOTE: This function can only be called when synchronous calls are allowed.
312 // See ScopedDisallowBlockingCalls for details.
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200313 // NOTE: Blocking calls are DISCOURAGED, consider if what you're doing can
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100314 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200315 virtual void BlockingCall(FunctionView<void()> functor);
316
317 template <typename Functor,
318 typename ReturnT = std::invoke_result_t<Functor>,
319 typename = typename std::enable_if_t<!std::is_void_v<ReturnT>>>
320 ReturnT BlockingCall(Functor&& functor) {
Danil Chapovalov89313452019-11-29 12:56:43 +0100321 ReturnT result;
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200322 BlockingCall([&] { result = std::forward<Functor>(functor)(); });
Danil Chapovalov89313452019-11-29 12:56:43 +0100323 return result;
324 }
325
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200326 // Deprecated, use `BlockingCall` instead.
327 template <typename ReturnT>
Danil Chapovalov9e09a1f2022-09-08 18:38:10 +0200328 [[deprecated]] ReturnT Invoke(const Location& /*posted_from*/,
329 FunctionView<ReturnT()> functor) {
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200330 return BlockingCall(functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200331 }
332
Danil Chapovalov7c323ad2022-09-08 13:13:53 +0200333 // Allows BlockingCall to specified `thread`. Thread never will be
334 // dereferenced and will be used only for reference-based comparison, so
335 // instance can be safely deleted. If NDEBUG is defined and RTC_DCHECK_IS_ON
336 // is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200337 void AllowInvokesToThread(Thread* thread);
Tomas Gunnarssonabdb4702020-09-05 18:43:36 +0200338
Mirko Bonadei481e3452021-07-30 13:57:25 +0200339 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined do nothing.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200340 void DisallowAllInvokes();
Artem Titov96e3b992021-07-26 16:03:14 +0200341 // Returns true if `target` was allowed by AllowInvokesToThread() or if no
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200342 // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
343 // returns false.
Mirko Bonadei481e3452021-07-30 13:57:25 +0200344 // If NDEBUG is defined and RTC_DCHECK_IS_ON is undefined always returns
Mirko Bonadei8c185fc2021-07-21 13:12:38 +0200345 // true.
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200346 bool IsInvokeToThreadAllowed(rtc::Thread* target);
347
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100348 // From TaskQueueBase
Danil Chapovalov4bcf8092022-07-06 19:42:34 +0200349 void Delete() override;
350 void PostTask(absl::AnyInvocable<void() &&> task) override;
351 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
352 webrtc::TimeDelta delay) override;
353 void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
354 webrtc::TimeDelta delay) override;
355
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200356 // ProcessMessages will process I/O and dispatch messages until:
357 // 1) cms milliseconds have elapsed (returns true)
358 // 2) Stop() is called (returns false)
359 bool ProcessMessages(int cms);
360
361 // Returns true if this is a thread that we created using the standard
362 // constructor, false if it was created by a call to
363 // ThreadManager::WrapCurrentThread(). The main thread of an application
364 // is generally not owned, since the OS representation of the thread
365 // obviously exists before we can get to it.
366 // You cannot call Start on non-owned threads.
367 bool IsOwned();
368
Tommi51492422017-12-04 15:18:23 +0100369 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200370 //
371 // DANGER: this is a terrible public API. Most callers that might want to
372 // call this likely do not have enough control/knowledge of the Thread in
373 // question to guarantee that the returned value remains true for the duration
374 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100375 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200376
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200377 // These functions are public to avoid injecting test hooks. Don't call them
378 // outside of tests.
379 // This method should be called when thread is created using non standard
380 // method, like derived implementation of rtc::Thread and it can not be
381 // started by calling Start(). This will set started flag to true and
382 // owned to false. This must be called from the current thread.
383 bool WrapCurrent();
384 void UnwrapCurrent();
385
Karl Wiberg32562252019-02-21 13:38:30 +0100386 // Sets the per-thread allow-blocking-calls flag to false; this is
387 // irrevocable. Must be called on this thread.
388 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
389
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200390 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100391 class CurrentThreadSetter : CurrentTaskQueueSetter {
392 public:
393 explicit CurrentThreadSetter(Thread* thread)
394 : CurrentTaskQueueSetter(thread),
395 manager_(rtc::ThreadManager::Instance()),
396 previous_(manager_->CurrentThread()) {
397 manager_->ChangeCurrentThreadForTest(thread);
398 }
399 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
400
401 private:
402 rtc::ThreadManager* const manager_;
403 rtc::Thread* const previous_;
404 };
405
Sebastian Jansson61380c02020-01-17 14:46:08 +0100406 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
407 // with the same trigger time are processed in num_ (FIFO) order.
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200408 struct DelayedMessage {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100409 bool operator<(const DelayedMessage& dmsg) const {
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200410 return (dmsg.run_time_ms < run_time_ms) ||
411 ((dmsg.run_time_ms == run_time_ms) &&
412 (dmsg.message_number < message_number));
Sebastian Jansson61380c02020-01-17 14:46:08 +0100413 }
414
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200415 int64_t delay_ms; // for debugging
416 int64_t run_time_ms;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100417 // Monotonicaly incrementing number used for ordering of messages
418 // targeted to execute at the same time.
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200419 uint32_t message_number;
420 // std::priority_queue doesn't allow to extract elements, but functor
421 // is move-only and thus need to be changed when pulled out of the
422 // priority queue. That is ok because `functor` doesn't affect operator<
423 mutable absl::AnyInvocable<void() &&> functor;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100424 };
425
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100426 // Perform initialization, subclasses must call this from their constructor
427 // if false was passed as init_queue to the Thread constructor.
428 void DoInit();
429
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100430 // Perform cleanup; subclasses must call this from the destructor,
431 // and are not expected to actually hold the lock.
432 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
433
434 void WakeUpSocketServer();
435
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200436 // Same as WrapCurrent except that it never fails as it does not try to
437 // acquire the synchronization access of the thread. The caller should never
438 // call Stop() or Join() on this thread.
439 void SafeWrapCurrent();
440
441 // Blocks the calling thread until this thread has terminated.
442 void Join();
443
444 static void AssertBlockingIsAllowedOnCurrentThread();
445
446 friend class ScopedDisallowBlockingCalls;
447
448 private:
Harald Alvestrandba694422021-01-27 21:52:14 +0000449 static const int kSlowDispatchLoggingThreshold = 50; // 50 ms
450
Danil Chapovalov207f8532022-08-24 12:19:46 +0200451 // Get() will process I/O until:
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200452 // 1) A task is available (returns it)
453 // 2) cmsWait seconds have elapsed (returns empty task)
454 // 3) Stop() is called (returns empty task)
455 absl::AnyInvocable<void() &&> Get(int cmsWait);
456 void Dispatch(absl::AnyInvocable<void() &&> task);
Danil Chapovalov207f8532022-08-24 12:19:46 +0200457
Karl Wiberg32562252019-02-21 13:38:30 +0100458 // Sets the per-thread allow-blocking-calls flag and returns the previous
459 // value. Must be called on this thread.
460 bool SetAllowBlockingCalls(bool allow);
461
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200462#if defined(WEBRTC_WIN)
463 static DWORD WINAPI PreRun(LPVOID context);
464#else
Yves Gerey665174f2018-06-19 15:03:05 +0200465 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200466#endif
467
468 // ThreadManager calls this instead WrapCurrent() because
469 // ThreadManager::Instance() cannot be used while ThreadManager is
470 // being created.
471 // The method tries to get synchronization rights of the thread on Windows if
Artem Titov96e3b992021-07-26 16:03:14 +0200472 // `need_synchronize_access` is true.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200473 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
474 bool need_synchronize_access);
475
Tommi51492422017-12-04 15:18:23 +0100476 // Return true if the thread is currently running.
477 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200478
Tommi6866dc72020-05-15 10:11:56 +0200479 // Called by the ThreadManager when being set as the current thread.
480 void EnsureIsCurrentTaskQueue();
481
482 // Called by the ThreadManager when being unset as the current thread.
483 void ClearCurrentTaskQueue();
484
Danil Chapovalovd44e3412022-09-16 17:26:10 +0200485 std::queue<absl::AnyInvocable<void() &&>> messages_ RTC_GUARDED_BY(crit_);
486 std::priority_queue<DelayedMessage> delayed_messages_ RTC_GUARDED_BY(crit_);
Sebastian Jansson61380c02020-01-17 14:46:08 +0100487 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Tommife041642021-04-07 10:08:28 +0200488#if RTC_DCHECK_IS_ON
489 uint32_t blocking_call_count_ RTC_GUARDED_BY(this) = 0;
490 uint32_t could_be_blocking_call_count_ RTC_GUARDED_BY(this) = 0;
Artem Titovdfc5f0d2020-07-03 12:09:26 +0200491 std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
492 bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
493#endif
Markus Handell3cb525b2020-07-16 16:16:09 +0200494 RecursiveCriticalSection crit_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100495 bool fInitialized_;
496 bool fDestroyed_;
497
Niels Möller7a669002022-06-27 09:47:02 +0200498 std::atomic<int> stop_;
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100499
500 // The SocketServer might not be owned by Thread.
501 SocketServer* const ss_;
Artem Titov96e3b992021-07-26 16:03:14 +0200502 // Used if SocketServer ownership lies with `this`.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100503 std::unique_ptr<SocketServer> own_ss_;
504
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200505 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100506
Jonas Olssona4d87372019-07-05 19:08:33 +0200507 // TODO(tommi): Add thread checks for proper use of control methods.
508 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200509
510#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100511 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200512#endif
513
514#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100515 HANDLE thread_ = nullptr;
516 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200517#endif
518
Tommi51492422017-12-04 15:18:23 +0100519 // Indicates whether or not ownership of the worker thread lies with
520 // this instance or not. (i.e. owned_ == !wrapped).
521 // Must only be modified when the worker thread is not running.
522 bool owned_ = true;
523
524 // Only touched from the worker thread itself.
525 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200526
Tommi6866dc72020-05-15 10:11:56 +0200527 std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
528 task_queue_registration_;
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100529
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200530 friend class ThreadManager;
531
Harald Alvestrandba694422021-01-27 21:52:14 +0000532 int dispatch_warning_ms_ RTC_GUARDED_BY(this) = kSlowDispatchLoggingThreshold;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200533};
534
535// AutoThread automatically installs itself at construction
536// uninstalls at destruction, if a Thread object is
537// _not already_ associated with the current OS thread.
Tomas Gunnarsson0fd4c4e2020-09-04 16:33:25 +0200538//
539// NOTE: *** This class should only be used by tests ***
540//
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200541class AutoThread : public Thread {
542 public:
543 AutoThread();
544 ~AutoThread() override;
545
Byoungchan Lee14af7622022-01-12 05:24:58 +0900546 AutoThread(const AutoThread&) = delete;
547 AutoThread& operator=(const AutoThread&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200548};
549
550// AutoSocketServerThread automatically installs itself at
551// construction and uninstalls at destruction. If a Thread object is
552// already associated with the current OS thread, it is temporarily
553// disassociated and restored by the destructor.
554
555class AutoSocketServerThread : public Thread {
556 public:
557 explicit AutoSocketServerThread(SocketServer* ss);
558 ~AutoSocketServerThread() override;
559
Byoungchan Lee14af7622022-01-12 05:24:58 +0900560 AutoSocketServerThread(const AutoSocketServerThread&) = delete;
561 AutoSocketServerThread& operator=(const AutoSocketServerThread&) = delete;
562
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200563 private:
564 rtc::Thread* old_thread_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200565};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200566} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000567
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200568#endif // RTC_BASE_THREAD_H_