blob: f8b41d16b6b68791854d536275f7cb11f207ddbb [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);
231 virtual void Post(const Location& posted_from,
232 MessageHandler* phandler,
233 uint32_t id = 0,
234 MessageData* pdata = nullptr,
235 bool time_sensitive = false);
236 virtual void PostDelayed(const Location& posted_from,
237 int cmsDelay,
238 MessageHandler* phandler,
239 uint32_t id = 0,
240 MessageData* pdata = nullptr);
241 virtual void PostAt(const Location& posted_from,
242 int64_t tstamp,
243 MessageHandler* phandler,
244 uint32_t id = 0,
245 MessageData* pdata = nullptr);
246 // TODO(honghaiz): Remove this when all the dependencies are removed.
247 virtual void PostAt(const Location& posted_from,
248 uint32_t tstamp,
249 MessageHandler* phandler,
250 uint32_t id = 0,
251 MessageData* pdata = nullptr);
252 virtual void Clear(MessageHandler* phandler,
253 uint32_t id = MQID_ANY,
254 MessageList* removed = nullptr);
255 virtual void Dispatch(Message* pmsg);
256 virtual void ReceiveSends();
257
258 // Amount of time until the next message can be retrieved
259 virtual int GetDelay();
260
261 bool empty() const { return size() == 0u; }
262 size_t size() const {
263 CritScope cs(&crit_); // msgq_.size() is not thread safe.
264 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
265 }
266
267 // Internally posts a message which causes the doomed object to be deleted
268 template <class T>
269 void Dispose(T* doomed) {
270 if (doomed) {
271 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
272 }
273 }
274
275 // When this signal is sent out, any references to this queue should
276 // no longer be used.
277 sigslot::signal0<> SignalQueueDestroyed;
278
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200279 bool IsCurrent() const;
280
281 // Sleeps the calling thread for the specified number of milliseconds, during
282 // which time no processing is performed. Returns false if sleeping was
283 // interrupted by a signal (POSIX only).
284 static bool SleepMs(int millis);
285
286 // Sets the thread's name, for debugging. Must be called before Start().
287 // If |obj| is non-null, its value is appended to |name|.
288 const std::string& name() const { return name_; }
289 bool SetName(const std::string& name, const void* obj);
290
291 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200292 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293
294 // Tells the thread to stop and waits until it is joined.
295 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100296 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200297 // underlying OS thread.
298 virtual void Stop();
299
300 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
301 // work, override Run(). To receive and dispatch messages, call
302 // ProcessMessages occasionally.
303 virtual void Run();
304
305 virtual void Send(const Location& posted_from,
306 MessageHandler* phandler,
307 uint32_t id = 0,
308 MessageData* pdata = nullptr);
309
310 // Convenience method to invoke a functor on another thread. Caller must
311 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
312 // Uses Send() internally, which blocks the current thread until execution
313 // is complete.
314 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
315 // &MyFunctionReturningBool);
316 // NOTE: This function can only be called when synchronous calls are allowed.
317 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100318 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
319 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100320 template <
321 class ReturnT,
322 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
323 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
324 ReturnT result;
325 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
326 return result;
327 }
328
329 template <
330 class ReturnT,
331 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
332 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
333 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200334 }
335
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100336 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
337 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200338 // is passed and (usually, see below) destroyed on |this| thread after it is
339 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100340 // Requirements of FunctorT:
341 // - FunctorT is movable.
342 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
343 // (if T is not void, the return value is discarded on |this| thread).
344 // - FunctorT has a public destructor that can be invoked from |this| thread
345 // after operation() has been invoked.
346 // - The functor must not cause the thread to quit before PostTask() is done.
347 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200348 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
349 // the task is run, it will be destroyed on |this| thread. However, if there
350 // are pending tasks by the time the Thread is destroyed, or a task is posted
351 // to a thread that is quitting, the task is destroyed immediately, on the
352 // calling thread. Destroying the Thread only blocks for any currently running
353 // task to complete. Note that TQ abstraction is even vaguer on how
354 // destruction happens in these cases, allowing destruction to happen
355 // asynchronously at a later time and on some arbitrary thread. So to ease
356 // migration, don't depend on Thread::PostTask destroying un-run tasks
357 // immediately.
358 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100359 // Example - Calling a class method:
360 // class Foo {
361 // public:
362 // void DoTheThing();
363 // };
364 // Foo foo;
365 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
366 //
367 // Example - Calling a lambda function:
368 // thread->PostTask(RTC_FROM_HERE,
369 // [&x, &y] { x.TrackComputations(y.Compute()); });
370 template <class FunctorT>
371 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800372 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200373 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100374 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100375 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800376 template <class FunctorT>
377 void PostDelayedTask(const Location& posted_from,
378 FunctorT&& functor,
379 uint32_t milliseconds) {
380 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
381 /*id=*/0,
382 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
383 std::forward<FunctorT>(functor)));
384 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100385
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100386 // From TaskQueueBase
387 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
388 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
389 uint32_t milliseconds) override;
390 void Delete() override;
391
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200392 // ProcessMessages will process I/O and dispatch messages until:
393 // 1) cms milliseconds have elapsed (returns true)
394 // 2) Stop() is called (returns false)
395 bool ProcessMessages(int cms);
396
397 // Returns true if this is a thread that we created using the standard
398 // constructor, false if it was created by a call to
399 // ThreadManager::WrapCurrentThread(). The main thread of an application
400 // is generally not owned, since the OS representation of the thread
401 // obviously exists before we can get to it.
402 // You cannot call Start on non-owned threads.
403 bool IsOwned();
404
Tommi51492422017-12-04 15:18:23 +0100405 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406 //
407 // DANGER: this is a terrible public API. Most callers that might want to
408 // call this likely do not have enough control/knowledge of the Thread in
409 // question to guarantee that the returned value remains true for the duration
410 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100411 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200412
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200413 // These functions are public to avoid injecting test hooks. Don't call them
414 // outside of tests.
415 // This method should be called when thread is created using non standard
416 // method, like derived implementation of rtc::Thread and it can not be
417 // started by calling Start(). This will set started flag to true and
418 // owned to false. This must be called from the current thread.
419 bool WrapCurrent();
420 void UnwrapCurrent();
421
Karl Wiberg32562252019-02-21 13:38:30 +0100422 // Sets the per-thread allow-blocking-calls flag to false; this is
423 // irrevocable. Must be called on this thread.
424 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
425
426#ifdef WEBRTC_ANDROID
427 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
428 // invariants upheld by DisallowBlockingCalls() and
429 // ScopedDisallowBlockingCalls. Must be called on this thread.
430 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
431#endif
432
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200433 protected:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100434 class PriorityQueue : public std::priority_queue<DelayedMessage> {
435 public:
436 container_type& container() { return c; }
437 void reheap() { make_heap(c.begin(), c.end(), comp); }
438 };
439
440 void DoDelayPost(const Location& posted_from,
441 int64_t cmsDelay,
442 int64_t tstamp,
443 MessageHandler* phandler,
444 uint32_t id,
445 MessageData* pdata);
446
447 // Perform initialization, subclasses must call this from their constructor
448 // if false was passed as init_queue to the Thread constructor.
449 void DoInit();
450
451 // Does not take any lock. Must be called either while holding crit_, or by
452 // the destructor (by definition, the latter has exclusive access).
453 void ClearInternal(MessageHandler* phandler,
454 uint32_t id,
455 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
456
457 // Perform cleanup; subclasses must call this from the destructor,
458 // and are not expected to actually hold the lock.
459 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
460
461 void WakeUpSocketServer();
462
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200463 // Same as WrapCurrent except that it never fails as it does not try to
464 // acquire the synchronization access of the thread. The caller should never
465 // call Stop() or Join() on this thread.
466 void SafeWrapCurrent();
467
468 // Blocks the calling thread until this thread has terminated.
469 void Join();
470
471 static void AssertBlockingIsAllowedOnCurrentThread();
472
473 friend class ScopedDisallowBlockingCalls;
474
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100475 CriticalSection* CritForTest() { return &crit_; }
476
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200477 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100478 class QueuedTaskHandler final : public MessageHandler {
479 public:
480 void OnMessage(Message* msg) override;
481 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800482
Karl Wiberg32562252019-02-21 13:38:30 +0100483 // Sets the per-thread allow-blocking-calls flag and returns the previous
484 // value. Must be called on this thread.
485 bool SetAllowBlockingCalls(bool allow);
486
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200487#if defined(WEBRTC_WIN)
488 static DWORD WINAPI PreRun(LPVOID context);
489#else
Yves Gerey665174f2018-06-19 15:03:05 +0200490 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200491#endif
492
493 // ThreadManager calls this instead WrapCurrent() because
494 // ThreadManager::Instance() cannot be used while ThreadManager is
495 // being created.
496 // The method tries to get synchronization rights of the thread on Windows if
497 // |need_synchronize_access| is true.
498 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
499 bool need_synchronize_access);
500
Tommi51492422017-12-04 15:18:23 +0100501 // Return true if the thread is currently running.
502 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200503
504 // Processes received "Send" requests. If |source| is not null, only requests
505 // from |source| are processed, otherwise, all requests are processed.
506 void ReceiveSendsFromThread(const Thread* source);
507
508 // If |source| is not null, pops the first "Send" message from |source| in
509 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
510 // The caller must lock |crit_| before calling.
511 // Returns true if there is such a message.
512 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
513
Danil Chapovalov89313452019-11-29 12:56:43 +0100514 void InvokeInternal(const Location& posted_from,
515 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200516
Steve Antonbcc1a762019-12-11 11:21:53 -0800517 // Returns a static-lifetime MessageHandler which runs message with
518 // MessageLikeTask payload data.
519 static MessageHandler* GetPostTaskMessageHandler();
520
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100521 bool fPeekKeep_;
522 Message msgPeek_;
523 MessageList msgq_ RTC_GUARDED_BY(crit_);
524 PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
525 uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
526 CriticalSection crit_;
527 bool fInitialized_;
528 bool fDestroyed_;
529
530 volatile int stop_;
531
532 // The SocketServer might not be owned by Thread.
533 SocketServer* const ss_;
534 // Used if SocketServer ownership lies with |this|.
535 std::unique_ptr<SocketServer> own_ss_;
536
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200537 std::list<_SendMessage> sendlist_;
538 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100539
Jonas Olssona4d87372019-07-05 19:08:33 +0200540 // TODO(tommi): Add thread checks for proper use of control methods.
541 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200542
543#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100544 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200545#endif
546
547#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100548 HANDLE thread_ = nullptr;
549 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200550#endif
551
Tommi51492422017-12-04 15:18:23 +0100552 // Indicates whether or not ownership of the worker thread lies with
553 // this instance or not. (i.e. owned_ == !wrapped).
554 // Must only be modified when the worker thread is not running.
555 bool owned_ = true;
556
557 // Only touched from the worker thread itself.
558 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200559
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100560 // Runs webrtc::QueuedTask posted to the Thread.
561 QueuedTaskHandler queued_task_handler_;
562
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200563 friend class ThreadManager;
564
565 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
566};
567
568// AutoThread automatically installs itself at construction
569// uninstalls at destruction, if a Thread object is
570// _not already_ associated with the current OS thread.
571
572class AutoThread : public Thread {
573 public:
574 AutoThread();
575 ~AutoThread() override;
576
577 private:
578 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
579};
580
581// AutoSocketServerThread automatically installs itself at
582// construction and uninstalls at destruction. If a Thread object is
583// already associated with the current OS thread, it is temporarily
584// disassociated and restored by the destructor.
585
586class AutoSocketServerThread : public Thread {
587 public:
588 explicit AutoSocketServerThread(SocketServer* ss);
589 ~AutoSocketServerThread() override;
590
591 private:
592 rtc::Thread* old_thread_;
593
594 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
595};
596
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100597// TODO(srte): Remove these when all dependencies has been updated.
598using MessageQueue = Thread;
599using MessageQueueManager = ThreadManager;
600
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200601} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000602
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200603#endif // RTC_BASE_THREAD_H_