blob: b8af583e78bb644d263a0ecb3fa1f5614b667144 [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);
93
94 // Returns a thread object with its thread_ ivar set
95 // to whatever the OS uses to represent the thread.
96 // If there already *is* a Thread object corresponding to this thread,
97 // this method will return that. Otherwise it creates a new Thread
98 // object whose wrapped() method will return true, and whose
99 // handle will, on Win32, be opened with only synchronization privileges -
100 // if you need more privilegs, rather than changing this method, please
101 // write additional code to adjust the privileges, or call a different
102 // factory method of your own devising, because this one gets used in
103 // unexpected contexts (like inside browser plugins) and it would be a
104 // shame to break it. It is also conceivable on Win32 that we won't even
105 // be able to get synchronization privileges, in which case the result
106 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200107 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200108 void UnwrapCurrentThread();
109
Niels Moller9d1840c2019-05-21 07:26:37 +0000110 bool IsMainThread();
111
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200112 private:
113 ThreadManager();
114 ~ThreadManager();
115
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100116 void AddInternal(Thread* message_queue);
117 void RemoveInternal(Thread* message_queue);
118 void ClearInternal(MessageHandler* handler);
119 void ProcessAllMessageQueuesInternal();
120
121 // This list contains all live Threads.
122 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
123
124 // Methods that don't modify the list of message queues may be called in a
125 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
126 // calls.
127 CriticalSection crit_;
128 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
129
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200130#if defined(WEBRTC_POSIX)
131 pthread_key_t key_;
132#endif
133
134#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100135 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200136#endif
137
Niels Moller9d1840c2019-05-21 07:26:37 +0000138 // The thread to potentially autowrap.
139 const PlatformThreadRef main_thread_ref_;
140
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200141 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
142};
143
144struct _SendMessage {
145 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200146 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200147 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200148 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200149};
150
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
152
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100153class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700154 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100155 static const int kForever = -1;
156
157 // Create a new Thread and optionally assign it to the passed
158 // SocketServer. Subclasses that override Clear should pass false for
159 // init_queue and call DoInit() from their constructor to prevent races
160 // with the ThreadManager using the object while the vtable is still
161 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200162 explicit Thread(SocketServer* ss);
163 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100164
Taylor Brandstetter08672602018-03-02 15:20:33 -0800165 // Constructors meant for subclasses; they should call DoInit themselves and
166 // pass false for |do_init|, so that DoInit is called only on the fully
167 // instantiated class, which avoids a vptr data race.
168 Thread(SocketServer* ss, bool do_init);
169 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170
171 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
172 // guarantee Stop() is explicitly called before the subclass is destroyed).
173 // This is required to avoid a data race between the destructor modifying the
174 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100175
176 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
177 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
178 // between the destructor modifying the vtable, and the ThreadManager
179 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200180 ~Thread() override;
181
182 static std::unique_ptr<Thread> CreateWithSocketServer();
183 static std::unique_ptr<Thread> Create();
184 static Thread* Current();
185
186 // Used to catch performance regressions. Use this to disallow blocking calls
187 // (Invoke) for a given scope. If a synchronous call is made while this is in
188 // effect, an assert will be triggered.
189 // Note that this is a single threaded class.
190 class ScopedDisallowBlockingCalls {
191 public:
192 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100193 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
194 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
195 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200196 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200197
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 private:
199 Thread* const thread_;
200 const bool previous_state_;
201 };
202
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100203 SocketServer* socketserver();
204
205 // Note: The behavior of Thread has changed. When a thread is stopped,
206 // futher Posts and Sends will fail. However, any pending Sends and *ready*
207 // Posts (as opposed to unexpired delayed Posts) will be delivered before
208 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
209 // we eliminate the race condition when an MessageHandler and Thread
210 // may be destroyed independently of each other.
211 virtual void Quit();
212 virtual bool IsQuitting();
213 virtual void Restart();
214 // Not all message queues actually process messages (such as SignalThread).
215 // In those cases, it's important to know, before posting, that it won't be
216 // Processed. Normally, this would be true until IsQuitting() is true.
217 virtual bool IsProcessingMessagesForTesting();
218
219 // Get() will process I/O until:
220 // 1) A message is available (returns true)
221 // 2) cmsWait seconds have elapsed (returns false)
222 // 3) Stop() is called (returns false)
223 virtual bool Get(Message* pmsg,
224 int cmsWait = kForever,
225 bool process_io = true);
226 virtual bool Peek(Message* pmsg, int cmsWait = 0);
227 virtual void Post(const Location& posted_from,
228 MessageHandler* phandler,
229 uint32_t id = 0,
230 MessageData* pdata = nullptr,
231 bool time_sensitive = false);
232 virtual void PostDelayed(const Location& posted_from,
233 int cmsDelay,
234 MessageHandler* phandler,
235 uint32_t id = 0,
236 MessageData* pdata = nullptr);
237 virtual void PostAt(const Location& posted_from,
238 int64_t tstamp,
239 MessageHandler* phandler,
240 uint32_t id = 0,
241 MessageData* pdata = nullptr);
242 // TODO(honghaiz): Remove this when all the dependencies are removed.
243 virtual void PostAt(const Location& posted_from,
244 uint32_t tstamp,
245 MessageHandler* phandler,
246 uint32_t id = 0,
247 MessageData* pdata = nullptr);
248 virtual void Clear(MessageHandler* phandler,
249 uint32_t id = MQID_ANY,
250 MessageList* removed = nullptr);
251 virtual void Dispatch(Message* pmsg);
252 virtual void ReceiveSends();
253
254 // Amount of time until the next message can be retrieved
255 virtual int GetDelay();
256
257 bool empty() const { return size() == 0u; }
258 size_t size() const {
259 CritScope cs(&crit_); // msgq_.size() is not thread safe.
260 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
261 }
262
263 // Internally posts a message which causes the doomed object to be deleted
264 template <class T>
265 void Dispose(T* doomed) {
266 if (doomed) {
267 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
268 }
269 }
270
271 // When this signal is sent out, any references to this queue should
272 // no longer be used.
273 sigslot::signal0<> SignalQueueDestroyed;
274
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200275 bool IsCurrent() const;
276
277 // Sleeps the calling thread for the specified number of milliseconds, during
278 // which time no processing is performed. Returns false if sleeping was
279 // interrupted by a signal (POSIX only).
280 static bool SleepMs(int millis);
281
282 // Sets the thread's name, for debugging. Must be called before Start().
283 // If |obj| is non-null, its value is appended to |name|.
284 const std::string& name() const { return name_; }
285 bool SetName(const std::string& name, const void* obj);
286
287 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200288 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200289
290 // Tells the thread to stop and waits until it is joined.
291 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100292 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293 // underlying OS thread.
294 virtual void Stop();
295
296 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
297 // work, override Run(). To receive and dispatch messages, call
298 // ProcessMessages occasionally.
299 virtual void Run();
300
301 virtual void Send(const Location& posted_from,
302 MessageHandler* phandler,
303 uint32_t id = 0,
304 MessageData* pdata = nullptr);
305
306 // Convenience method to invoke a functor on another thread. Caller must
307 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
308 // Uses Send() internally, which blocks the current thread until execution
309 // is complete.
310 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
311 // &MyFunctionReturningBool);
312 // NOTE: This function can only be called when synchronous calls are allowed.
313 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100314 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
315 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100316 template <
317 class ReturnT,
318 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
319 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
320 ReturnT result;
321 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
322 return result;
323 }
324
325 template <
326 class ReturnT,
327 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
328 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
329 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200330 }
331
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100332 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
333 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200334 // is passed and (usually, see below) destroyed on |this| thread after it is
335 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100336 // Requirements of FunctorT:
337 // - FunctorT is movable.
338 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
339 // (if T is not void, the return value is discarded on |this| thread).
340 // - FunctorT has a public destructor that can be invoked from |this| thread
341 // after operation() has been invoked.
342 // - The functor must not cause the thread to quit before PostTask() is done.
343 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200344 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
345 // the task is run, it will be destroyed on |this| thread. However, if there
346 // are pending tasks by the time the Thread is destroyed, or a task is posted
347 // to a thread that is quitting, the task is destroyed immediately, on the
348 // calling thread. Destroying the Thread only blocks for any currently running
349 // task to complete. Note that TQ abstraction is even vaguer on how
350 // destruction happens in these cases, allowing destruction to happen
351 // asynchronously at a later time and on some arbitrary thread. So to ease
352 // migration, don't depend on Thread::PostTask destroying un-run tasks
353 // immediately.
354 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100355 // Example - Calling a class method:
356 // class Foo {
357 // public:
358 // void DoTheThing();
359 // };
360 // Foo foo;
361 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
362 //
363 // Example - Calling a lambda function:
364 // thread->PostTask(RTC_FROM_HERE,
365 // [&x, &y] { x.TrackComputations(y.Compute()); });
366 template <class FunctorT>
367 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800368 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200369 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100370 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100371 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800372 template <class FunctorT>
373 void PostDelayedTask(const Location& posted_from,
374 FunctorT&& functor,
375 uint32_t milliseconds) {
376 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
377 /*id=*/0,
378 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
379 std::forward<FunctorT>(functor)));
380 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100381
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100382 // From TaskQueueBase
383 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
384 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
385 uint32_t milliseconds) override;
386 void Delete() override;
387
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200388 // ProcessMessages will process I/O and dispatch messages until:
389 // 1) cms milliseconds have elapsed (returns true)
390 // 2) Stop() is called (returns false)
391 bool ProcessMessages(int cms);
392
393 // Returns true if this is a thread that we created using the standard
394 // constructor, false if it was created by a call to
395 // ThreadManager::WrapCurrentThread(). The main thread of an application
396 // is generally not owned, since the OS representation of the thread
397 // obviously exists before we can get to it.
398 // You cannot call Start on non-owned threads.
399 bool IsOwned();
400
Tommi51492422017-12-04 15:18:23 +0100401 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200402 //
403 // DANGER: this is a terrible public API. Most callers that might want to
404 // call this likely do not have enough control/knowledge of the Thread in
405 // question to guarantee that the returned value remains true for the duration
406 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100407 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200408
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200409 // These functions are public to avoid injecting test hooks. Don't call them
410 // outside of tests.
411 // This method should be called when thread is created using non standard
412 // method, like derived implementation of rtc::Thread and it can not be
413 // started by calling Start(). This will set started flag to true and
414 // owned to false. This must be called from the current thread.
415 bool WrapCurrent();
416 void UnwrapCurrent();
417
Karl Wiberg32562252019-02-21 13:38:30 +0100418 // Sets the per-thread allow-blocking-calls flag to false; this is
419 // irrevocable. Must be called on this thread.
420 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
421
422#ifdef WEBRTC_ANDROID
423 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
424 // invariants upheld by DisallowBlockingCalls() and
425 // ScopedDisallowBlockingCalls. Must be called on this thread.
426 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
427#endif
428
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200429 protected:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100430 class PriorityQueue : public std::priority_queue<DelayedMessage> {
431 public:
432 container_type& container() { return c; }
433 void reheap() { make_heap(c.begin(), c.end(), comp); }
434 };
435
436 void DoDelayPost(const Location& posted_from,
437 int64_t cmsDelay,
438 int64_t tstamp,
439 MessageHandler* phandler,
440 uint32_t id,
441 MessageData* pdata);
442
443 // Perform initialization, subclasses must call this from their constructor
444 // if false was passed as init_queue to the Thread constructor.
445 void DoInit();
446
447 // Does not take any lock. Must be called either while holding crit_, or by
448 // the destructor (by definition, the latter has exclusive access).
449 void ClearInternal(MessageHandler* phandler,
450 uint32_t id,
451 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
452
453 // Perform cleanup; subclasses must call this from the destructor,
454 // and are not expected to actually hold the lock.
455 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
456
457 void WakeUpSocketServer();
458
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200459 // Same as WrapCurrent except that it never fails as it does not try to
460 // acquire the synchronization access of the thread. The caller should never
461 // call Stop() or Join() on this thread.
462 void SafeWrapCurrent();
463
464 // Blocks the calling thread until this thread has terminated.
465 void Join();
466
467 static void AssertBlockingIsAllowedOnCurrentThread();
468
469 friend class ScopedDisallowBlockingCalls;
470
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100471 CriticalSection* CritForTest() { return &crit_; }
472
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200473 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100474 class QueuedTaskHandler final : public MessageHandler {
475 public:
476 void OnMessage(Message* msg) override;
477 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800478
Karl Wiberg32562252019-02-21 13:38:30 +0100479 // Sets the per-thread allow-blocking-calls flag and returns the previous
480 // value. Must be called on this thread.
481 bool SetAllowBlockingCalls(bool allow);
482
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200483#if defined(WEBRTC_WIN)
484 static DWORD WINAPI PreRun(LPVOID context);
485#else
Yves Gerey665174f2018-06-19 15:03:05 +0200486 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200487#endif
488
489 // ThreadManager calls this instead WrapCurrent() because
490 // ThreadManager::Instance() cannot be used while ThreadManager is
491 // being created.
492 // The method tries to get synchronization rights of the thread on Windows if
493 // |need_synchronize_access| is true.
494 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
495 bool need_synchronize_access);
496
Tommi51492422017-12-04 15:18:23 +0100497 // Return true if the thread is currently running.
498 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200499
500 // Processes received "Send" requests. If |source| is not null, only requests
501 // from |source| are processed, otherwise, all requests are processed.
502 void ReceiveSendsFromThread(const Thread* source);
503
504 // If |source| is not null, pops the first "Send" message from |source| in
505 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
506 // The caller must lock |crit_| before calling.
507 // Returns true if there is such a message.
508 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
509
Danil Chapovalov89313452019-11-29 12:56:43 +0100510 void InvokeInternal(const Location& posted_from,
511 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200512
Steve Antonbcc1a762019-12-11 11:21:53 -0800513 // Returns a static-lifetime MessageHandler which runs message with
514 // MessageLikeTask payload data.
515 static MessageHandler* GetPostTaskMessageHandler();
516
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100517 bool fPeekKeep_;
518 Message msgPeek_;
519 MessageList msgq_ RTC_GUARDED_BY(crit_);
520 PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
521 uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
522 CriticalSection crit_;
523 bool fInitialized_;
524 bool fDestroyed_;
525
526 volatile int stop_;
527
528 // The SocketServer might not be owned by Thread.
529 SocketServer* const ss_;
530 // Used if SocketServer ownership lies with |this|.
531 std::unique_ptr<SocketServer> own_ss_;
532
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200533 std::list<_SendMessage> sendlist_;
534 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100535
Jonas Olssona4d87372019-07-05 19:08:33 +0200536 // TODO(tommi): Add thread checks for proper use of control methods.
537 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200538
539#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100540 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200541#endif
542
543#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100544 HANDLE thread_ = nullptr;
545 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200546#endif
547
Tommi51492422017-12-04 15:18:23 +0100548 // Indicates whether or not ownership of the worker thread lies with
549 // this instance or not. (i.e. owned_ == !wrapped).
550 // Must only be modified when the worker thread is not running.
551 bool owned_ = true;
552
553 // Only touched from the worker thread itself.
554 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200555
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100556 // Runs webrtc::QueuedTask posted to the Thread.
557 QueuedTaskHandler queued_task_handler_;
558
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200559 friend class ThreadManager;
560
561 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
562};
563
564// AutoThread automatically installs itself at construction
565// uninstalls at destruction, if a Thread object is
566// _not already_ associated with the current OS thread.
567
568class AutoThread : public Thread {
569 public:
570 AutoThread();
571 ~AutoThread() override;
572
573 private:
574 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
575};
576
577// AutoSocketServerThread automatically installs itself at
578// construction and uninstalls at destruction. If a Thread object is
579// already associated with the current OS thread, it is temporarily
580// disassociated and restored by the destructor.
581
582class AutoSocketServerThread : public Thread {
583 public:
584 explicit AutoSocketServerThread(SocketServer* ss);
585 ~AutoSocketServerThread() override;
586
587 private:
588 rtc::Thread* old_thread_;
589
590 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
591};
592
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100593// TODO(srte): Remove these when all dependencies has been updated.
594using MessageQueue = Thread;
595using MessageQueueManager = ThreadManager;
596
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200597} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000598
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200599#endif // RTC_BASE_THREAD_H_