blob: 77aff611f981738f23ec0c66c7d1867bbf174c89 [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 Jansson61380c02020-01-17 14:46:08 +0100428 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
429 // with the same trigger time are processed in num_ (FIFO) order.
430 class DelayedMessage {
431 public:
432 DelayedMessage(int64_t delay,
433 int64_t run_time_ms,
434 uint32_t num,
435 const Message& msg)
436 : delay_ms_(delay),
437 run_time_ms_(run_time_ms),
438 message_number_(num),
439 msg_(msg) {}
440
441 bool operator<(const DelayedMessage& dmsg) const {
442 return (dmsg.run_time_ms_ < run_time_ms_) ||
443 ((dmsg.run_time_ms_ == run_time_ms_) &&
444 (dmsg.message_number_ < message_number_));
445 }
446
447 int64_t delay_ms_; // for debugging
448 int64_t run_time_ms_;
449 // Monotonicaly incrementing number used for ordering of messages
450 // targeted to execute at the same time.
451 uint32_t message_number_;
452 Message msg_;
453 };
454
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100455 class PriorityQueue : public std::priority_queue<DelayedMessage> {
456 public:
457 container_type& container() { return c; }
458 void reheap() { make_heap(c.begin(), c.end(), comp); }
459 };
460
461 void DoDelayPost(const Location& posted_from,
462 int64_t cmsDelay,
463 int64_t tstamp,
464 MessageHandler* phandler,
465 uint32_t id,
466 MessageData* pdata);
467
468 // Perform initialization, subclasses must call this from their constructor
469 // if false was passed as init_queue to the Thread constructor.
470 void DoInit();
471
472 // Does not take any lock. Must be called either while holding crit_, or by
473 // the destructor (by definition, the latter has exclusive access).
474 void ClearInternal(MessageHandler* phandler,
475 uint32_t id,
476 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
477
478 // Perform cleanup; subclasses must call this from the destructor,
479 // and are not expected to actually hold the lock.
480 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
481
482 void WakeUpSocketServer();
483
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200484 // Same as WrapCurrent except that it never fails as it does not try to
485 // acquire the synchronization access of the thread. The caller should never
486 // call Stop() or Join() on this thread.
487 void SafeWrapCurrent();
488
489 // Blocks the calling thread until this thread has terminated.
490 void Join();
491
492 static void AssertBlockingIsAllowedOnCurrentThread();
493
494 friend class ScopedDisallowBlockingCalls;
495
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100496 CriticalSection* CritForTest() { return &crit_; }
497
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200498 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100499 class QueuedTaskHandler final : public MessageHandler {
500 public:
501 void OnMessage(Message* msg) override;
502 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800503
Karl Wiberg32562252019-02-21 13:38:30 +0100504 // Sets the per-thread allow-blocking-calls flag and returns the previous
505 // value. Must be called on this thread.
506 bool SetAllowBlockingCalls(bool allow);
507
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200508#if defined(WEBRTC_WIN)
509 static DWORD WINAPI PreRun(LPVOID context);
510#else
Yves Gerey665174f2018-06-19 15:03:05 +0200511 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200512#endif
513
514 // ThreadManager calls this instead WrapCurrent() because
515 // ThreadManager::Instance() cannot be used while ThreadManager is
516 // being created.
517 // The method tries to get synchronization rights of the thread on Windows if
518 // |need_synchronize_access| is true.
519 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
520 bool need_synchronize_access);
521
Tommi51492422017-12-04 15:18:23 +0100522 // Return true if the thread is currently running.
523 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200524
525 // Processes received "Send" requests. If |source| is not null, only requests
526 // from |source| are processed, otherwise, all requests are processed.
527 void ReceiveSendsFromThread(const Thread* source);
528
529 // If |source| is not null, pops the first "Send" message from |source| in
530 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
531 // The caller must lock |crit_| before calling.
532 // Returns true if there is such a message.
533 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
534
Danil Chapovalov89313452019-11-29 12:56:43 +0100535 void InvokeInternal(const Location& posted_from,
536 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200537
Steve Antonbcc1a762019-12-11 11:21:53 -0800538 // Returns a static-lifetime MessageHandler which runs message with
539 // MessageLikeTask payload data.
540 static MessageHandler* GetPostTaskMessageHandler();
541
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100542 bool fPeekKeep_;
543 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100544 MessageList messages_ RTC_GUARDED_BY(crit_);
545 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
546 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100547 CriticalSection crit_;
548 bool fInitialized_;
549 bool fDestroyed_;
550
551 volatile int stop_;
552
553 // The SocketServer might not be owned by Thread.
554 SocketServer* const ss_;
555 // Used if SocketServer ownership lies with |this|.
556 std::unique_ptr<SocketServer> own_ss_;
557
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200558 std::list<_SendMessage> sendlist_;
559 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100560
Jonas Olssona4d87372019-07-05 19:08:33 +0200561 // TODO(tommi): Add thread checks for proper use of control methods.
562 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200563
564#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100565 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200566#endif
567
568#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100569 HANDLE thread_ = nullptr;
570 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200571#endif
572
Tommi51492422017-12-04 15:18:23 +0100573 // Indicates whether or not ownership of the worker thread lies with
574 // this instance or not. (i.e. owned_ == !wrapped).
575 // Must only be modified when the worker thread is not running.
576 bool owned_ = true;
577
578 // Only touched from the worker thread itself.
579 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200580
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100581 // Runs webrtc::QueuedTask posted to the Thread.
582 QueuedTaskHandler queued_task_handler_;
583
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200584 friend class ThreadManager;
585
586 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
587};
588
589// AutoThread automatically installs itself at construction
590// uninstalls at destruction, if a Thread object is
591// _not already_ associated with the current OS thread.
592
593class AutoThread : public Thread {
594 public:
595 AutoThread();
596 ~AutoThread() override;
597
598 private:
599 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
600};
601
602// AutoSocketServerThread automatically installs itself at
603// construction and uninstalls at destruction. If a Thread object is
604// already associated with the current OS thread, it is temporarily
605// disassociated and restored by the destructor.
606
607class AutoSocketServerThread : public Thread {
608 public:
609 explicit AutoSocketServerThread(SocketServer* ss);
610 ~AutoSocketServerThread() override;
611
612 private:
613 rtc::Thread* old_thread_;
614
615 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
616};
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200617} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000618
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200619#endif // RTC_BASE_THREAD_H_