blob: d08c3bd09c60d284f3f4b0162b43f5e01166da5d [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>
17#include <memory>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010018#include <queue>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020019#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020020#include <type_traits>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010021#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020023#if defined(WEBRTC_POSIX)
24#include <pthread.h>
25#endif
Danil Chapovalov89313452019-11-29 12:56:43 +010026#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010027#include "api/task_queue/queued_task.h"
28#include "api/task_queue/task_queue_base.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/constructor_magic.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010030#include "rtc_base/critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020031#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020035#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020036#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010037#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020038
39#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020041#endif
42
43namespace rtc {
44
45class Thread;
46
Henrik Boströmba4dcc32019-02-28 09:34:06 +010047namespace rtc_thread_internal {
48
Niels Möllerf13a0962019-05-17 10:15:06 +020049class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010050 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020051 virtual void Run() = 0;
52};
53
54template <class FunctorT>
55class MessageWithFunctor final : public MessageLikeTask {
56 public:
57 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010058 : functor_(std::forward<FunctorT>(functor)) {}
59
Niels Möllerf13a0962019-05-17 10:15:06 +020060 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010061
62 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020063 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010064
65 typename std::remove_reference<FunctorT>::type functor_;
66
Niels Möllerf13a0962019-05-17 10:15:06 +020067 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
68};
69
Henrik Boströmba4dcc32019-02-28 09:34:06 +010070} // namespace rtc_thread_internal
71
Mirko Bonadei35214fc2019-09-23 14:54:28 +020072class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020073 public:
74 static const int kForever = -1;
75
76 // Singleton, constructor and destructor are private.
77 static ThreadManager* Instance();
78
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010079 static void Add(Thread* message_queue);
80 static void Remove(Thread* message_queue);
81 static void Clear(MessageHandler* handler);
82
83 // TODO(nisse): Delete alias, as soon as downstream code is updated.
84 static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); }
85
86 // For testing purposes, for use with a simulated clock.
87 // Ensures that all message queues have processed delayed messages
88 // up until the current point in time.
89 static void ProcessAllMessageQueuesForTesting();
90
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091 Thread* CurrentThread();
92 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +010093 // Allows changing the current thread, this is intended for tests where we
94 // want to simulate multiple threads running on a single physical thread.
95 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020096
97 // Returns a thread object with its thread_ ivar set
98 // to whatever the OS uses to represent the thread.
99 // If there already *is* a Thread object corresponding to this thread,
100 // this method will return that. Otherwise it creates a new Thread
101 // object whose wrapped() method will return true, and whose
102 // handle will, on Win32, be opened with only synchronization privileges -
103 // if you need more privilegs, rather than changing this method, please
104 // write additional code to adjust the privileges, or call a different
105 // factory method of your own devising, because this one gets used in
106 // unexpected contexts (like inside browser plugins) and it would be a
107 // shame to break it. It is also conceivable on Win32 that we won't even
108 // be able to get synchronization privileges, in which case the result
109 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200110 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 void UnwrapCurrentThread();
112
Niels Moller9d1840c2019-05-21 07:26:37 +0000113 bool IsMainThread();
114
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200115 private:
116 ThreadManager();
117 ~ThreadManager();
118
Sebastian Jansson178a6852020-01-14 11:12:26 +0100119 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100120 void AddInternal(Thread* message_queue);
121 void RemoveInternal(Thread* message_queue);
122 void ClearInternal(MessageHandler* handler);
123 void ProcessAllMessageQueuesInternal();
124
125 // This list contains all live Threads.
126 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
127
128 // Methods that don't modify the list of message queues may be called in a
129 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
130 // calls.
131 CriticalSection crit_;
132 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
133
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134#if defined(WEBRTC_POSIX)
135 pthread_key_t key_;
136#endif
137
138#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100139 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140#endif
141
Niels Moller9d1840c2019-05-21 07:26:37 +0000142 // The thread to potentially autowrap.
143 const PlatformThreadRef main_thread_ref_;
144
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
146};
147
148struct _SendMessage {
149 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200150 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200152 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200153};
154
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
156
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100157class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700158 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100159 static const int kForever = -1;
160
161 // Create a new Thread and optionally assign it to the passed
162 // SocketServer. Subclasses that override Clear should pass false for
163 // init_queue and call DoInit() from their constructor to prevent races
164 // with the ThreadManager using the object while the vtable is still
165 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166 explicit Thread(SocketServer* ss);
167 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100168
Taylor Brandstetter08672602018-03-02 15:20:33 -0800169 // Constructors meant for subclasses; they should call DoInit themselves and
170 // pass false for |do_init|, so that DoInit is called only on the fully
171 // instantiated class, which avoids a vptr data race.
172 Thread(SocketServer* ss, bool do_init);
173 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200174
175 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
176 // guarantee Stop() is explicitly called before the subclass is destroyed).
177 // This is required to avoid a data race between the destructor modifying the
178 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100179
180 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
181 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
182 // between the destructor modifying the vtable, and the ThreadManager
183 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200184 ~Thread() override;
185
186 static std::unique_ptr<Thread> CreateWithSocketServer();
187 static std::unique_ptr<Thread> Create();
188 static Thread* Current();
189
190 // Used to catch performance regressions. Use this to disallow blocking calls
191 // (Invoke) for a given scope. If a synchronous call is made while this is in
192 // effect, an assert will be triggered.
193 // Note that this is a single threaded class.
194 class ScopedDisallowBlockingCalls {
195 public:
196 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100197 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
198 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
199 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200200 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200201
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200202 private:
203 Thread* const thread_;
204 const bool previous_state_;
205 };
206
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100207 SocketServer* socketserver();
208
209 // Note: The behavior of Thread has changed. When a thread is stopped,
210 // futher Posts and Sends will fail. However, any pending Sends and *ready*
211 // Posts (as opposed to unexpired delayed Posts) will be delivered before
212 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
213 // we eliminate the race condition when an MessageHandler and Thread
214 // may be destroyed independently of each other.
215 virtual void Quit();
216 virtual bool IsQuitting();
217 virtual void Restart();
218 // Not all message queues actually process messages (such as SignalThread).
219 // In those cases, it's important to know, before posting, that it won't be
220 // Processed. Normally, this would be true until IsQuitting() is true.
221 virtual bool IsProcessingMessagesForTesting();
222
223 // Get() will process I/O until:
224 // 1) A message is available (returns true)
225 // 2) cmsWait seconds have elapsed (returns false)
226 // 3) Stop() is called (returns false)
227 virtual bool Get(Message* pmsg,
228 int cmsWait = kForever,
229 bool process_io = true);
230 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Sebastian Jansson61380c02020-01-17 14:46:08 +0100231 // |time_sensitive| is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100232 virtual void Post(const Location& posted_from,
233 MessageHandler* phandler,
234 uint32_t id = 0,
235 MessageData* pdata = nullptr,
236 bool time_sensitive = false);
237 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100238 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100239 MessageHandler* phandler,
240 uint32_t id = 0,
241 MessageData* pdata = nullptr);
242 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100243 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100244 MessageHandler* phandler,
245 uint32_t id = 0,
246 MessageData* pdata = nullptr);
247 virtual void Clear(MessageHandler* phandler,
248 uint32_t id = MQID_ANY,
249 MessageList* removed = nullptr);
250 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100251
252 // Amount of time until the next message can be retrieved
253 virtual int GetDelay();
254
255 bool empty() const { return size() == 0u; }
256 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100257 CritScope cs(&crit_);
258 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100259 }
260
261 // Internally posts a message which causes the doomed object to be deleted
262 template <class T>
263 void Dispose(T* doomed) {
264 if (doomed) {
265 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
266 }
267 }
268
269 // When this signal is sent out, any references to this queue should
270 // no longer be used.
271 sigslot::signal0<> SignalQueueDestroyed;
272
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200273 bool IsCurrent() const;
274
275 // Sleeps the calling thread for the specified number of milliseconds, during
276 // which time no processing is performed. Returns false if sleeping was
277 // interrupted by a signal (POSIX only).
278 static bool SleepMs(int millis);
279
280 // Sets the thread's name, for debugging. Must be called before Start().
281 // If |obj| is non-null, its value is appended to |name|.
282 const std::string& name() const { return name_; }
283 bool SetName(const std::string& name, const void* obj);
284
285 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200286 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200287
288 // Tells the thread to stop and waits until it is joined.
289 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100290 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200291 // underlying OS thread.
292 virtual void Stop();
293
294 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
295 // work, override Run(). To receive and dispatch messages, call
296 // ProcessMessages occasionally.
297 virtual void Run();
298
299 virtual void Send(const Location& posted_from,
300 MessageHandler* phandler,
301 uint32_t id = 0,
302 MessageData* pdata = nullptr);
303
304 // Convenience method to invoke a functor on another thread. Caller must
305 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
306 // Uses Send() internally, which blocks the current thread until execution
307 // is complete.
308 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
309 // &MyFunctionReturningBool);
310 // NOTE: This function can only be called when synchronous calls are allowed.
311 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100312 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
313 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100314 template <
315 class ReturnT,
316 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
317 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
318 ReturnT result;
319 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
320 return result;
321 }
322
323 template <
324 class ReturnT,
325 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
326 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
327 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200328 }
329
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100330 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
331 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200332 // is passed and (usually, see below) destroyed on |this| thread after it is
333 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100334 // Requirements of FunctorT:
335 // - FunctorT is movable.
336 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
337 // (if T is not void, the return value is discarded on |this| thread).
338 // - FunctorT has a public destructor that can be invoked from |this| thread
339 // after operation() has been invoked.
340 // - The functor must not cause the thread to quit before PostTask() is done.
341 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200342 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
343 // the task is run, it will be destroyed on |this| thread. However, if there
344 // are pending tasks by the time the Thread is destroyed, or a task is posted
345 // to a thread that is quitting, the task is destroyed immediately, on the
346 // calling thread. Destroying the Thread only blocks for any currently running
347 // task to complete. Note that TQ abstraction is even vaguer on how
348 // destruction happens in these cases, allowing destruction to happen
349 // asynchronously at a later time and on some arbitrary thread. So to ease
350 // migration, don't depend on Thread::PostTask destroying un-run tasks
351 // immediately.
352 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100353 // Example - Calling a class method:
354 // class Foo {
355 // public:
356 // void DoTheThing();
357 // };
358 // Foo foo;
359 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
360 //
361 // Example - Calling a lambda function:
362 // thread->PostTask(RTC_FROM_HERE,
363 // [&x, &y] { x.TrackComputations(y.Compute()); });
364 template <class FunctorT>
365 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800366 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200367 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100368 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100369 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800370 template <class FunctorT>
371 void PostDelayedTask(const Location& posted_from,
372 FunctorT&& functor,
373 uint32_t milliseconds) {
374 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
375 /*id=*/0,
376 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
377 std::forward<FunctorT>(functor)));
378 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100379
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100380 // From TaskQueueBase
381 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
382 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
383 uint32_t milliseconds) override;
384 void Delete() override;
385
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200386 // ProcessMessages will process I/O and dispatch messages until:
387 // 1) cms milliseconds have elapsed (returns true)
388 // 2) Stop() is called (returns false)
389 bool ProcessMessages(int cms);
390
391 // Returns true if this is a thread that we created using the standard
392 // constructor, false if it was created by a call to
393 // ThreadManager::WrapCurrentThread(). The main thread of an application
394 // is generally not owned, since the OS representation of the thread
395 // obviously exists before we can get to it.
396 // You cannot call Start on non-owned threads.
397 bool IsOwned();
398
Tommi51492422017-12-04 15:18:23 +0100399 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200400 //
401 // DANGER: this is a terrible public API. Most callers that might want to
402 // call this likely do not have enough control/knowledge of the Thread in
403 // question to guarantee that the returned value remains true for the duration
404 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100405 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200407 // These functions are public to avoid injecting test hooks. Don't call them
408 // outside of tests.
409 // This method should be called when thread is created using non standard
410 // method, like derived implementation of rtc::Thread and it can not be
411 // started by calling Start(). This will set started flag to true and
412 // owned to false. This must be called from the current thread.
413 bool WrapCurrent();
414 void UnwrapCurrent();
415
Karl Wiberg32562252019-02-21 13:38:30 +0100416 // Sets the per-thread allow-blocking-calls flag to false; this is
417 // irrevocable. Must be called on this thread.
418 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
419
420#ifdef WEBRTC_ANDROID
421 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
422 // invariants upheld by DisallowBlockingCalls() and
423 // ScopedDisallowBlockingCalls. Must be called on this thread.
424 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
425#endif
426
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200427 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100428 class CurrentThreadSetter : CurrentTaskQueueSetter {
429 public:
430 explicit CurrentThreadSetter(Thread* thread)
431 : CurrentTaskQueueSetter(thread),
432 manager_(rtc::ThreadManager::Instance()),
433 previous_(manager_->CurrentThread()) {
434 manager_->ChangeCurrentThreadForTest(thread);
435 }
436 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
437
438 private:
439 rtc::ThreadManager* const manager_;
440 rtc::Thread* const previous_;
441 };
442
Sebastian Jansson61380c02020-01-17 14:46:08 +0100443 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
444 // with the same trigger time are processed in num_ (FIFO) order.
445 class DelayedMessage {
446 public:
447 DelayedMessage(int64_t delay,
448 int64_t run_time_ms,
449 uint32_t num,
450 const Message& msg)
451 : delay_ms_(delay),
452 run_time_ms_(run_time_ms),
453 message_number_(num),
454 msg_(msg) {}
455
456 bool operator<(const DelayedMessage& dmsg) const {
457 return (dmsg.run_time_ms_ < run_time_ms_) ||
458 ((dmsg.run_time_ms_ == run_time_ms_) &&
459 (dmsg.message_number_ < message_number_));
460 }
461
462 int64_t delay_ms_; // for debugging
463 int64_t run_time_ms_;
464 // Monotonicaly incrementing number used for ordering of messages
465 // targeted to execute at the same time.
466 uint32_t message_number_;
467 Message msg_;
468 };
469
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100470 class PriorityQueue : public std::priority_queue<DelayedMessage> {
471 public:
472 container_type& container() { return c; }
473 void reheap() { make_heap(c.begin(), c.end(), comp); }
474 };
475
476 void DoDelayPost(const Location& posted_from,
477 int64_t cmsDelay,
478 int64_t tstamp,
479 MessageHandler* phandler,
480 uint32_t id,
481 MessageData* pdata);
482
483 // Perform initialization, subclasses must call this from their constructor
484 // if false was passed as init_queue to the Thread constructor.
485 void DoInit();
486
487 // Does not take any lock. Must be called either while holding crit_, or by
488 // the destructor (by definition, the latter has exclusive access).
489 void ClearInternal(MessageHandler* phandler,
490 uint32_t id,
491 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
492
493 // Perform cleanup; subclasses must call this from the destructor,
494 // and are not expected to actually hold the lock.
495 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
496
497 void WakeUpSocketServer();
498
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200499 // Same as WrapCurrent except that it never fails as it does not try to
500 // acquire the synchronization access of the thread. The caller should never
501 // call Stop() or Join() on this thread.
502 void SafeWrapCurrent();
503
504 // Blocks the calling thread until this thread has terminated.
505 void Join();
506
507 static void AssertBlockingIsAllowedOnCurrentThread();
508
509 friend class ScopedDisallowBlockingCalls;
510
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100511 CriticalSection* CritForTest() { return &crit_; }
512
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200513 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100514 class QueuedTaskHandler final : public MessageHandler {
515 public:
516 void OnMessage(Message* msg) override;
517 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800518
Karl Wiberg32562252019-02-21 13:38:30 +0100519 // Sets the per-thread allow-blocking-calls flag and returns the previous
520 // value. Must be called on this thread.
521 bool SetAllowBlockingCalls(bool allow);
522
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200523#if defined(WEBRTC_WIN)
524 static DWORD WINAPI PreRun(LPVOID context);
525#else
Yves Gerey665174f2018-06-19 15:03:05 +0200526 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200527#endif
528
529 // ThreadManager calls this instead WrapCurrent() because
530 // ThreadManager::Instance() cannot be used while ThreadManager is
531 // being created.
532 // The method tries to get synchronization rights of the thread on Windows if
533 // |need_synchronize_access| is true.
534 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
535 bool need_synchronize_access);
536
Tommi51492422017-12-04 15:18:23 +0100537 // Return true if the thread is currently running.
538 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200539
540 // Processes received "Send" requests. If |source| is not null, only requests
541 // from |source| are processed, otherwise, all requests are processed.
542 void ReceiveSendsFromThread(const Thread* source);
543
544 // If |source| is not null, pops the first "Send" message from |source| in
545 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
546 // The caller must lock |crit_| before calling.
547 // Returns true if there is such a message.
548 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
549
Danil Chapovalov89313452019-11-29 12:56:43 +0100550 void InvokeInternal(const Location& posted_from,
551 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200552
Steve Antonbcc1a762019-12-11 11:21:53 -0800553 // Returns a static-lifetime MessageHandler which runs message with
554 // MessageLikeTask payload data.
555 static MessageHandler* GetPostTaskMessageHandler();
556
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100557 bool fPeekKeep_;
558 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100559 MessageList messages_ RTC_GUARDED_BY(crit_);
560 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
561 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100562 CriticalSection crit_;
563 bool fInitialized_;
564 bool fDestroyed_;
565
566 volatile int stop_;
567
568 // The SocketServer might not be owned by Thread.
569 SocketServer* const ss_;
570 // Used if SocketServer ownership lies with |this|.
571 std::unique_ptr<SocketServer> own_ss_;
572
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200573 std::list<_SendMessage> sendlist_;
574 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100575
Jonas Olssona4d87372019-07-05 19:08:33 +0200576 // TODO(tommi): Add thread checks for proper use of control methods.
577 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200578
579#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100580 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200581#endif
582
583#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100584 HANDLE thread_ = nullptr;
585 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200586#endif
587
Tommi51492422017-12-04 15:18:23 +0100588 // Indicates whether or not ownership of the worker thread lies with
589 // this instance or not. (i.e. owned_ == !wrapped).
590 // Must only be modified when the worker thread is not running.
591 bool owned_ = true;
592
593 // Only touched from the worker thread itself.
594 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200595
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100596 // Runs webrtc::QueuedTask posted to the Thread.
597 QueuedTaskHandler queued_task_handler_;
598
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200599 friend class ThreadManager;
600
601 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
602};
603
604// AutoThread automatically installs itself at construction
605// uninstalls at destruction, if a Thread object is
606// _not already_ associated with the current OS thread.
607
608class AutoThread : public Thread {
609 public:
610 AutoThread();
611 ~AutoThread() override;
612
613 private:
614 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
615};
616
617// AutoSocketServerThread automatically installs itself at
618// construction and uninstalls at destruction. If a Thread object is
619// already associated with the current OS thread, it is temporarily
620// disassociated and restored by the destructor.
621
622class AutoSocketServerThread : public Thread {
623 public:
624 explicit AutoSocketServerThread(SocketServer* ss);
625 ~AutoSocketServerThread() override;
626
627 private:
628 rtc::Thread* old_thread_;
629
630 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
631};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200632} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000633
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200634#endif // RTC_BASE_THREAD_H_