blob: 74aab623c874cdda543aa6e4463ffa3a0e6e5205 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_THREAD_H_
12#define RTC_BASE_THREAD_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <list>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010017#include <map>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#include <memory>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010019#include <queue>
Sebastian Janssonda7267a2020-03-03 10:48:05 +010020#include <set>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020021#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020022#include <type_traits>
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010023#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025#if defined(WEBRTC_POSIX)
26#include <pthread.h>
27#endif
Danil Chapovalov89313452019-11-29 12:56:43 +010028#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010029#include "api/task_queue/queued_task.h"
30#include "api/task_queue/task_queue_base.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/constructor_magic.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010032#include "rtc_base/critical_section.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "rtc_base/message_handler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020037#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020038#include "rtc_base/thread_annotations.h"
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010039#include "rtc_base/thread_message.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020040
41#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043#endif
44
45namespace rtc {
46
47class Thread;
48
Henrik Boströmba4dcc32019-02-28 09:34:06 +010049namespace rtc_thread_internal {
50
Niels Möllerf13a0962019-05-17 10:15:06 +020051class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010052 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020053 virtual void Run() = 0;
54};
55
56template <class FunctorT>
57class MessageWithFunctor final : public MessageLikeTask {
58 public:
59 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010060 : functor_(std::forward<FunctorT>(functor)) {}
61
Niels Möllerf13a0962019-05-17 10:15:06 +020062 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010063
64 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020065 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010066
67 typename std::remove_reference<FunctorT>::type functor_;
68
Niels Möllerf13a0962019-05-17 10:15:06 +020069 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
70};
71
Henrik Boströmba4dcc32019-02-28 09:34:06 +010072} // namespace rtc_thread_internal
73
Mirko Bonadei35214fc2019-09-23 14:54:28 +020074class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020075 public:
76 static const int kForever = -1;
77
78 // Singleton, constructor and destructor are private.
79 static ThreadManager* Instance();
80
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +010081 static void Add(Thread* message_queue);
82 static void Remove(Thread* message_queue);
83 static void Clear(MessageHandler* handler);
84
85 // TODO(nisse): Delete alias, as soon as downstream code is updated.
86 static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); }
87
88 // For testing purposes, for use with a simulated clock.
89 // Ensures that all message queues have processed delayed messages
90 // up until the current point in time.
91 static void ProcessAllMessageQueuesForTesting();
92
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020093 Thread* CurrentThread();
94 void SetCurrentThread(Thread* thread);
Sebastian Jansson178a6852020-01-14 11:12:26 +010095 // Allows changing the current thread, this is intended for tests where we
96 // want to simulate multiple threads running on a single physical thread.
97 void ChangeCurrentThreadForTest(Thread* thread);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020098
99 // Returns a thread object with its thread_ ivar set
100 // to whatever the OS uses to represent the thread.
101 // If there already *is* a Thread object corresponding to this thread,
102 // this method will return that. Otherwise it creates a new Thread
103 // object whose wrapped() method will return true, and whose
104 // handle will, on Win32, be opened with only synchronization privileges -
105 // if you need more privilegs, rather than changing this method, please
106 // write additional code to adjust the privileges, or call a different
107 // factory method of your own devising, because this one gets used in
108 // unexpected contexts (like inside browser plugins) and it would be a
109 // shame to break it. It is also conceivable on Win32 that we won't even
110 // be able to get synchronization privileges, in which case the result
111 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200112 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200113 void UnwrapCurrentThread();
114
Niels Moller9d1840c2019-05-21 07:26:37 +0000115 bool IsMainThread();
116
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100117#if RTC_DCHECK_IS_ON
118 // Registers that a Send operation is to be performed between |source| and
119 // |target|, while checking that this does not cause a send cycle that could
120 // potentially cause a deadlock.
121 void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
122#endif
123
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124 private:
125 ThreadManager();
126 ~ThreadManager();
127
Sebastian Jansson178a6852020-01-14 11:12:26 +0100128 void SetCurrentThreadInternal(Thread* thread);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100129 void AddInternal(Thread* message_queue);
130 void RemoveInternal(Thread* message_queue);
131 void ClearInternal(MessageHandler* handler);
132 void ProcessAllMessageQueuesInternal();
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100133#if RTC_DCHECK_IS_ON
134 void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
135#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100136
137 // This list contains all live Threads.
138 std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
139
140 // Methods that don't modify the list of message queues may be called in a
141 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
142 // calls.
143 CriticalSection crit_;
144 size_t processing_ RTC_GUARDED_BY(crit_) = 0;
Sebastian Janssonda7267a2020-03-03 10:48:05 +0100145#if RTC_DCHECK_IS_ON
146 // Represents all thread seand actions by storing all send targets per thread.
147 // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
148 // since we will trigger a CHECK failure if a cycle is introduced.
149 std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
150#endif
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100151
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200152#if defined(WEBRTC_POSIX)
153 pthread_key_t key_;
154#endif
155
156#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100157 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158#endif
159
Niels Moller9d1840c2019-05-21 07:26:37 +0000160 // The thread to potentially autowrap.
161 const PlatformThreadRef main_thread_ref_;
162
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200163 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
164};
165
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
167
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100168class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700169 public:
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100170 static const int kForever = -1;
171
172 // Create a new Thread and optionally assign it to the passed
173 // SocketServer. Subclasses that override Clear should pass false for
174 // init_queue and call DoInit() from their constructor to prevent races
175 // with the ThreadManager using the object while the vtable is still
176 // being created.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200177 explicit Thread(SocketServer* ss);
178 explicit Thread(std::unique_ptr<SocketServer> ss);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100179
Taylor Brandstetter08672602018-03-02 15:20:33 -0800180 // Constructors meant for subclasses; they should call DoInit themselves and
181 // pass false for |do_init|, so that DoInit is called only on the fully
182 // instantiated class, which avoids a vptr data race.
183 Thread(SocketServer* ss, bool do_init);
184 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185
186 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
187 // guarantee Stop() is explicitly called before the subclass is destroyed).
188 // This is required to avoid a data race between the destructor modifying the
189 // vtable, and the Thread::PreRun calling the virtual method Run().
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100190
191 // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
192 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
193 // between the destructor modifying the vtable, and the ThreadManager
194 // calling Clear on the object from a different thread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200195 ~Thread() override;
196
197 static std::unique_ptr<Thread> CreateWithSocketServer();
198 static std::unique_ptr<Thread> Create();
199 static Thread* Current();
200
201 // Used to catch performance regressions. Use this to disallow blocking calls
202 // (Invoke) for a given scope. If a synchronous call is made while this is in
203 // effect, an assert will be triggered.
204 // Note that this is a single threaded class.
205 class ScopedDisallowBlockingCalls {
206 public:
207 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100208 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
209 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
210 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200211 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200212
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200213 private:
214 Thread* const thread_;
215 const bool previous_state_;
216 };
217
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100218 SocketServer* socketserver();
219
220 // Note: The behavior of Thread has changed. When a thread is stopped,
221 // futher Posts and Sends will fail. However, any pending Sends and *ready*
222 // Posts (as opposed to unexpired delayed Posts) will be delivered before
223 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
224 // we eliminate the race condition when an MessageHandler and Thread
225 // may be destroyed independently of each other.
226 virtual void Quit();
227 virtual bool IsQuitting();
228 virtual void Restart();
229 // Not all message queues actually process messages (such as SignalThread).
230 // In those cases, it's important to know, before posting, that it won't be
231 // Processed. Normally, this would be true until IsQuitting() is true.
232 virtual bool IsProcessingMessagesForTesting();
233
234 // Get() will process I/O until:
235 // 1) A message is available (returns true)
236 // 2) cmsWait seconds have elapsed (returns false)
237 // 3) Stop() is called (returns false)
238 virtual bool Get(Message* pmsg,
239 int cmsWait = kForever,
240 bool process_io = true);
241 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Sebastian Jansson61380c02020-01-17 14:46:08 +0100242 // |time_sensitive| is deprecated and should always be false.
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100243 virtual void Post(const Location& posted_from,
244 MessageHandler* phandler,
245 uint32_t id = 0,
246 MessageData* pdata = nullptr,
247 bool time_sensitive = false);
248 virtual void PostDelayed(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100249 int delay_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100250 MessageHandler* phandler,
251 uint32_t id = 0,
252 MessageData* pdata = nullptr);
253 virtual void PostAt(const Location& posted_from,
Sebastian Jansson61380c02020-01-17 14:46:08 +0100254 int64_t run_at_ms,
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100255 MessageHandler* phandler,
256 uint32_t id = 0,
257 MessageData* pdata = nullptr);
258 virtual void Clear(MessageHandler* phandler,
259 uint32_t id = MQID_ANY,
260 MessageList* removed = nullptr);
261 virtual void Dispatch(Message* pmsg);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100262
263 // Amount of time until the next message can be retrieved
264 virtual int GetDelay();
265
266 bool empty() const { return size() == 0u; }
267 size_t size() const {
Sebastian Jansson61380c02020-01-17 14:46:08 +0100268 CritScope cs(&crit_);
269 return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100270 }
271
272 // Internally posts a message which causes the doomed object to be deleted
273 template <class T>
274 void Dispose(T* doomed) {
275 if (doomed) {
276 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
277 }
278 }
279
280 // When this signal is sent out, any references to this queue should
281 // no longer be used.
282 sigslot::signal0<> SignalQueueDestroyed;
283
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200284 bool IsCurrent() const;
285
286 // Sleeps the calling thread for the specified number of milliseconds, during
287 // which time no processing is performed. Returns false if sleeping was
288 // interrupted by a signal (POSIX only).
289 static bool SleepMs(int millis);
290
291 // Sets the thread's name, for debugging. Must be called before Start().
292 // If |obj| is non-null, its value is appended to |name|.
293 const std::string& name() const { return name_; }
294 bool SetName(const std::string& name, const void* obj);
295
296 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200297 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200298
299 // Tells the thread to stop and waits until it is joined.
300 // Never call Stop on the current thread. Instead use the inherited Quit
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100301 // function which will exit the base Thread without terminating the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200302 // underlying OS thread.
303 virtual void Stop();
304
305 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
306 // work, override Run(). To receive and dispatch messages, call
307 // ProcessMessages occasionally.
308 virtual void Run();
309
310 virtual void Send(const Location& posted_from,
311 MessageHandler* phandler,
312 uint32_t id = 0,
313 MessageData* pdata = nullptr);
314
315 // Convenience method to invoke a functor on another thread. Caller must
316 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
317 // Uses Send() internally, which blocks the current thread until execution
318 // is complete.
319 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
320 // &MyFunctionReturningBool);
321 // NOTE: This function can only be called when synchronous calls are allowed.
322 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100323 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
324 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100325 template <
326 class ReturnT,
327 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
328 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
329 ReturnT result;
330 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
331 return result;
332 }
333
334 template <
335 class ReturnT,
336 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
337 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
338 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200339 }
340
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100341 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
342 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200343 // is passed and (usually, see below) destroyed on |this| thread after it is
344 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100345 // Requirements of FunctorT:
346 // - FunctorT is movable.
347 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
348 // (if T is not void, the return value is discarded on |this| thread).
349 // - FunctorT has a public destructor that can be invoked from |this| thread
350 // after operation() has been invoked.
351 // - The functor must not cause the thread to quit before PostTask() is done.
352 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200353 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
354 // the task is run, it will be destroyed on |this| thread. However, if there
355 // are pending tasks by the time the Thread is destroyed, or a task is posted
356 // to a thread that is quitting, the task is destroyed immediately, on the
357 // calling thread. Destroying the Thread only blocks for any currently running
358 // task to complete. Note that TQ abstraction is even vaguer on how
359 // destruction happens in these cases, allowing destruction to happen
360 // asynchronously at a later time and on some arbitrary thread. So to ease
361 // migration, don't depend on Thread::PostTask destroying un-run tasks
362 // immediately.
363 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100364 // Example - Calling a class method:
365 // class Foo {
366 // public:
367 // void DoTheThing();
368 // };
369 // Foo foo;
370 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
371 //
372 // Example - Calling a lambda function:
373 // thread->PostTask(RTC_FROM_HERE,
374 // [&x, &y] { x.TrackComputations(y.Compute()); });
375 template <class FunctorT>
376 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800377 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200378 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100379 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100380 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800381 template <class FunctorT>
382 void PostDelayedTask(const Location& posted_from,
383 FunctorT&& functor,
384 uint32_t milliseconds) {
385 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
386 /*id=*/0,
387 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
388 std::forward<FunctorT>(functor)));
389 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100390
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100391 // From TaskQueueBase
392 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
393 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
394 uint32_t milliseconds) override;
395 void Delete() override;
396
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200397 // ProcessMessages will process I/O and dispatch messages until:
398 // 1) cms milliseconds have elapsed (returns true)
399 // 2) Stop() is called (returns false)
400 bool ProcessMessages(int cms);
401
402 // Returns true if this is a thread that we created using the standard
403 // constructor, false if it was created by a call to
404 // ThreadManager::WrapCurrentThread(). The main thread of an application
405 // is generally not owned, since the OS representation of the thread
406 // obviously exists before we can get to it.
407 // You cannot call Start on non-owned threads.
408 bool IsOwned();
409
Tommi51492422017-12-04 15:18:23 +0100410 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200411 //
412 // DANGER: this is a terrible public API. Most callers that might want to
413 // call this likely do not have enough control/knowledge of the Thread in
414 // question to guarantee that the returned value remains true for the duration
415 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100416 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200417
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200418 // These functions are public to avoid injecting test hooks. Don't call them
419 // outside of tests.
420 // This method should be called when thread is created using non standard
421 // method, like derived implementation of rtc::Thread and it can not be
422 // started by calling Start(). This will set started flag to true and
423 // owned to false. This must be called from the current thread.
424 bool WrapCurrent();
425 void UnwrapCurrent();
426
Karl Wiberg32562252019-02-21 13:38:30 +0100427 // Sets the per-thread allow-blocking-calls flag to false; this is
428 // irrevocable. Must be called on this thread.
429 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
430
431#ifdef WEBRTC_ANDROID
432 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
433 // invariants upheld by DisallowBlockingCalls() and
434 // ScopedDisallowBlockingCalls. Must be called on this thread.
435 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
436#endif
437
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200438 protected:
Sebastian Jansson6ce033a2020-01-22 10:12:56 +0100439 class CurrentThreadSetter : CurrentTaskQueueSetter {
440 public:
441 explicit CurrentThreadSetter(Thread* thread)
442 : CurrentTaskQueueSetter(thread),
443 manager_(rtc::ThreadManager::Instance()),
444 previous_(manager_->CurrentThread()) {
445 manager_->ChangeCurrentThreadForTest(thread);
446 }
447 ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
448
449 private:
450 rtc::ThreadManager* const manager_;
451 rtc::Thread* const previous_;
452 };
453
Sebastian Jansson61380c02020-01-17 14:46:08 +0100454 // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
455 // with the same trigger time are processed in num_ (FIFO) order.
456 class DelayedMessage {
457 public:
458 DelayedMessage(int64_t delay,
459 int64_t run_time_ms,
460 uint32_t num,
461 const Message& msg)
462 : delay_ms_(delay),
463 run_time_ms_(run_time_ms),
464 message_number_(num),
465 msg_(msg) {}
466
467 bool operator<(const DelayedMessage& dmsg) const {
468 return (dmsg.run_time_ms_ < run_time_ms_) ||
469 ((dmsg.run_time_ms_ == run_time_ms_) &&
470 (dmsg.message_number_ < message_number_));
471 }
472
473 int64_t delay_ms_; // for debugging
474 int64_t run_time_ms_;
475 // Monotonicaly incrementing number used for ordering of messages
476 // targeted to execute at the same time.
477 uint32_t message_number_;
478 Message msg_;
479 };
480
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100481 class PriorityQueue : public std::priority_queue<DelayedMessage> {
482 public:
483 container_type& container() { return c; }
484 void reheap() { make_heap(c.begin(), c.end(), comp); }
485 };
486
487 void DoDelayPost(const Location& posted_from,
488 int64_t cmsDelay,
489 int64_t tstamp,
490 MessageHandler* phandler,
491 uint32_t id,
492 MessageData* pdata);
493
494 // Perform initialization, subclasses must call this from their constructor
495 // if false was passed as init_queue to the Thread constructor.
496 void DoInit();
497
498 // Does not take any lock. Must be called either while holding crit_, or by
499 // the destructor (by definition, the latter has exclusive access).
500 void ClearInternal(MessageHandler* phandler,
501 uint32_t id,
502 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
503
504 // Perform cleanup; subclasses must call this from the destructor,
505 // and are not expected to actually hold the lock.
506 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
507
508 void WakeUpSocketServer();
509
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200510 // Same as WrapCurrent except that it never fails as it does not try to
511 // acquire the synchronization access of the thread. The caller should never
512 // call Stop() or Join() on this thread.
513 void SafeWrapCurrent();
514
515 // Blocks the calling thread until this thread has terminated.
516 void Join();
517
518 static void AssertBlockingIsAllowedOnCurrentThread();
519
520 friend class ScopedDisallowBlockingCalls;
521
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100522 CriticalSection* CritForTest() { return &crit_; }
523
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200524 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100525 class QueuedTaskHandler final : public MessageHandler {
526 public:
527 void OnMessage(Message* msg) override;
528 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800529
Karl Wiberg32562252019-02-21 13:38:30 +0100530 // Sets the per-thread allow-blocking-calls flag and returns the previous
531 // value. Must be called on this thread.
532 bool SetAllowBlockingCalls(bool allow);
533
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200534#if defined(WEBRTC_WIN)
535 static DWORD WINAPI PreRun(LPVOID context);
536#else
Yves Gerey665174f2018-06-19 15:03:05 +0200537 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200538#endif
539
540 // ThreadManager calls this instead WrapCurrent() because
541 // ThreadManager::Instance() cannot be used while ThreadManager is
542 // being created.
543 // The method tries to get synchronization rights of the thread on Windows if
544 // |need_synchronize_access| is true.
545 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
546 bool need_synchronize_access);
547
Tommi51492422017-12-04 15:18:23 +0100548 // Return true if the thread is currently running.
549 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200550
Danil Chapovalov89313452019-11-29 12:56:43 +0100551 void InvokeInternal(const Location& posted_from,
552 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200553
Steve Antonbcc1a762019-12-11 11:21:53 -0800554 // Returns a static-lifetime MessageHandler which runs message with
555 // MessageLikeTask payload data.
556 static MessageHandler* GetPostTaskMessageHandler();
557
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100558 bool fPeekKeep_;
559 Message msgPeek_;
Sebastian Jansson61380c02020-01-17 14:46:08 +0100560 MessageList messages_ RTC_GUARDED_BY(crit_);
561 PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
562 uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
Sebastian Jansson6ea2c6a2020-01-13 14:07:22 +0100563 CriticalSection crit_;
564 bool fInitialized_;
565 bool fDestroyed_;
566
567 volatile int stop_;
568
569 // The SocketServer might not be owned by Thread.
570 SocketServer* const ss_;
571 // Used if SocketServer ownership lies with |this|.
572 std::unique_ptr<SocketServer> own_ss_;
573
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200574 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_