blob: 186d7f4c4d0dfd9516fcafcc89d3a3780977aa47 [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>
18#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020019#include <type_traits>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020021#if defined(WEBRTC_POSIX)
22#include <pthread.h>
23#endif
Danil Chapovalov912b3b82019-11-22 15:52:40 +010024#include "api/task_queue/queued_task.h"
25#include "api/task_queue/task_queue_base.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/constructor_magic.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "rtc_base/message_handler.h"
29#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020032#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020033#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020034
35#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020037#endif
38
39namespace rtc {
40
41class Thread;
42
Henrik Boströmba4dcc32019-02-28 09:34:06 +010043namespace rtc_thread_internal {
44
Niels Möllerf13a0962019-05-17 10:15:06 +020045class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010046 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020047 virtual void Run() = 0;
48};
49
50template <class FunctorT>
51class MessageWithFunctor final : public MessageLikeTask {
52 public:
53 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010054 : functor_(std::forward<FunctorT>(functor)) {}
55
Niels Möllerf13a0962019-05-17 10:15:06 +020056 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010057
58 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020059 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010060
61 typename std::remove_reference<FunctorT>::type functor_;
62
Niels Möllerf13a0962019-05-17 10:15:06 +020063 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
64};
65
66class MessageHandlerWithTask final : public MessageHandler {
67 public:
68 MessageHandlerWithTask() = default;
69
70 void OnMessage(Message* msg) override {
71 static_cast<MessageLikeTask*>(msg->pdata)->Run();
72 delete msg->pdata;
73 }
74
75 private:
76 ~MessageHandlerWithTask() override {}
77
78 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
Henrik Boströmba4dcc32019-02-28 09:34:06 +010079};
80
81} // namespace rtc_thread_internal
82
Mirko Bonadei35214fc2019-09-23 14:54:28 +020083class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084 public:
85 static const int kForever = -1;
86
87 // Singleton, constructor and destructor are private.
88 static ThreadManager* Instance();
89
90 Thread* CurrentThread();
91 void SetCurrentThread(Thread* thread);
92
93 // Returns a thread object with its thread_ ivar set
94 // to whatever the OS uses to represent the thread.
95 // If there already *is* a Thread object corresponding to this thread,
96 // this method will return that. Otherwise it creates a new Thread
97 // object whose wrapped() method will return true, and whose
98 // handle will, on Win32, be opened with only synchronization privileges -
99 // if you need more privilegs, rather than changing this method, please
100 // write additional code to adjust the privileges, or call a different
101 // factory method of your own devising, because this one gets used in
102 // unexpected contexts (like inside browser plugins) and it would be a
103 // shame to break it. It is also conceivable on Win32 that we won't even
104 // be able to get synchronization privileges, in which case the result
105 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200106 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200107 void UnwrapCurrentThread();
108
Niels Moller9d1840c2019-05-21 07:26:37 +0000109 bool IsMainThread();
110
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 private:
112 ThreadManager();
113 ~ThreadManager();
114
115#if defined(WEBRTC_POSIX)
116 pthread_key_t key_;
117#endif
118
119#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100120 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200121#endif
122
Niels Moller9d1840c2019-05-21 07:26:37 +0000123 // The thread to potentially autowrap.
124 const PlatformThreadRef main_thread_ref_;
125
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200126 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
127};
128
129struct _SendMessage {
130 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200131 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200132 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200133 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134};
135
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200136// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
137
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100138class RTC_LOCKABLE RTC_EXPORT Thread : public MessageQueue,
139 public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700140 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200141 explicit Thread(SocketServer* ss);
142 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800143 // Constructors meant for subclasses; they should call DoInit themselves and
144 // pass false for |do_init|, so that DoInit is called only on the fully
145 // instantiated class, which avoids a vptr data race.
146 Thread(SocketServer* ss, bool do_init);
147 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148
149 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
150 // guarantee Stop() is explicitly called before the subclass is destroyed).
151 // This is required to avoid a data race between the destructor modifying the
152 // vtable, and the Thread::PreRun calling the virtual method Run().
153 ~Thread() override;
154
155 static std::unique_ptr<Thread> CreateWithSocketServer();
156 static std::unique_ptr<Thread> Create();
157 static Thread* Current();
158
159 // Used to catch performance regressions. Use this to disallow blocking calls
160 // (Invoke) for a given scope. If a synchronous call is made while this is in
161 // effect, an assert will be triggered.
162 // Note that this is a single threaded class.
163 class ScopedDisallowBlockingCalls {
164 public:
165 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100166 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
167 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
168 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200169 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200170
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200171 private:
172 Thread* const thread_;
173 const bool previous_state_;
174 };
175
176 bool IsCurrent() const;
177
178 // Sleeps the calling thread for the specified number of milliseconds, during
179 // which time no processing is performed. Returns false if sleeping was
180 // interrupted by a signal (POSIX only).
181 static bool SleepMs(int millis);
182
183 // Sets the thread's name, for debugging. Must be called before Start().
184 // If |obj| is non-null, its value is appended to |name|.
185 const std::string& name() const { return name_; }
186 bool SetName(const std::string& name, const void* obj);
187
188 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200189 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200190
191 // Tells the thread to stop and waits until it is joined.
192 // Never call Stop on the current thread. Instead use the inherited Quit
193 // function which will exit the base MessageQueue without terminating the
194 // underlying OS thread.
195 virtual void Stop();
196
197 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
198 // work, override Run(). To receive and dispatch messages, call
199 // ProcessMessages occasionally.
200 virtual void Run();
201
202 virtual void Send(const Location& posted_from,
203 MessageHandler* phandler,
204 uint32_t id = 0,
205 MessageData* pdata = nullptr);
206
207 // Convenience method to invoke a functor on another thread. Caller must
208 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
209 // Uses Send() internally, which blocks the current thread until execution
210 // is complete.
211 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
212 // &MyFunctionReturningBool);
213 // NOTE: This function can only be called when synchronous calls are allowed.
214 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100215 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
216 // be achieved with PostTask() and callbacks instead.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 template <class ReturnT, class FunctorT>
Karl Wibergd6b48192017-10-16 23:01:06 +0200218 ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {
219 FunctorMessageHandler<ReturnT, FunctorT> handler(
220 std::forward<FunctorT>(functor));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200221 InvokeInternal(posted_from, &handler);
222 return handler.MoveResult();
223 }
224
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100225 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
226 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200227 // is passed and (usually, see below) destroyed on |this| thread after it is
228 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100229 // Requirements of FunctorT:
230 // - FunctorT is movable.
231 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
232 // (if T is not void, the return value is discarded on |this| thread).
233 // - FunctorT has a public destructor that can be invoked from |this| thread
234 // after operation() has been invoked.
235 // - The functor must not cause the thread to quit before PostTask() is done.
236 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200237 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
238 // the task is run, it will be destroyed on |this| thread. However, if there
239 // are pending tasks by the time the Thread is destroyed, or a task is posted
240 // to a thread that is quitting, the task is destroyed immediately, on the
241 // calling thread. Destroying the Thread only blocks for any currently running
242 // task to complete. Note that TQ abstraction is even vaguer on how
243 // destruction happens in these cases, allowing destruction to happen
244 // asynchronously at a later time and on some arbitrary thread. So to ease
245 // migration, don't depend on Thread::PostTask destroying un-run tasks
246 // immediately.
247 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100248 // Example - Calling a class method:
249 // class Foo {
250 // public:
251 // void DoTheThing();
252 // };
253 // Foo foo;
254 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
255 //
256 // Example - Calling a lambda function:
257 // thread->PostTask(RTC_FROM_HERE,
258 // [&x, &y] { x.TrackComputations(y.Compute()); });
259 template <class FunctorT>
260 void PostTask(const Location& posted_from, FunctorT&& functor) {
Niels Möllerf13a0962019-05-17 10:15:06 +0200261 // Allocate at first call, never deallocate.
262 static auto* const handler =
263 new rtc_thread_internal::MessageHandlerWithTask;
264 Post(posted_from, handler, 0,
265 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100266 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100267 }
268
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100269 // From TaskQueueBase
270 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
271 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
272 uint32_t milliseconds) override;
273 void Delete() override;
274
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200275 // From MessageQueue
Niels Möller8909a632018-09-06 08:42:44 +0200276 bool IsProcessingMessagesForTesting() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200277 void Clear(MessageHandler* phandler,
278 uint32_t id = MQID_ANY,
279 MessageList* removed = nullptr) override;
280 void ReceiveSends() override;
281
282 // ProcessMessages will process I/O and dispatch messages until:
283 // 1) cms milliseconds have elapsed (returns true)
284 // 2) Stop() is called (returns false)
285 bool ProcessMessages(int cms);
286
287 // Returns true if this is a thread that we created using the standard
288 // constructor, false if it was created by a call to
289 // ThreadManager::WrapCurrentThread(). The main thread of an application
290 // is generally not owned, since the OS representation of the thread
291 // obviously exists before we can get to it.
292 // You cannot call Start on non-owned threads.
293 bool IsOwned();
294
Tommi51492422017-12-04 15:18:23 +0100295 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200296 //
297 // DANGER: this is a terrible public API. Most callers that might want to
298 // call this likely do not have enough control/knowledge of the Thread in
299 // question to guarantee that the returned value remains true for the duration
300 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100301 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200302
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200303 // These functions are public to avoid injecting test hooks. Don't call them
304 // outside of tests.
305 // This method should be called when thread is created using non standard
306 // method, like derived implementation of rtc::Thread and it can not be
307 // started by calling Start(). This will set started flag to true and
308 // owned to false. This must be called from the current thread.
309 bool WrapCurrent();
310 void UnwrapCurrent();
311
Karl Wiberg32562252019-02-21 13:38:30 +0100312 // Sets the per-thread allow-blocking-calls flag to false; this is
313 // irrevocable. Must be called on this thread.
314 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
315
316#ifdef WEBRTC_ANDROID
317 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
318 // invariants upheld by DisallowBlockingCalls() and
319 // ScopedDisallowBlockingCalls. Must be called on this thread.
320 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
321#endif
322
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200323 protected:
324 // Same as WrapCurrent except that it never fails as it does not try to
325 // acquire the synchronization access of the thread. The caller should never
326 // call Stop() or Join() on this thread.
327 void SafeWrapCurrent();
328
329 // Blocks the calling thread until this thread has terminated.
330 void Join();
331
332 static void AssertBlockingIsAllowedOnCurrentThread();
333
334 friend class ScopedDisallowBlockingCalls;
335
336 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100337 class QueuedTaskHandler final : public MessageHandler {
338 public:
339 void OnMessage(Message* msg) override;
340 };
Karl Wiberg32562252019-02-21 13:38:30 +0100341 // Sets the per-thread allow-blocking-calls flag and returns the previous
342 // value. Must be called on this thread.
343 bool SetAllowBlockingCalls(bool allow);
344
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200345#if defined(WEBRTC_WIN)
346 static DWORD WINAPI PreRun(LPVOID context);
347#else
Yves Gerey665174f2018-06-19 15:03:05 +0200348 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200349#endif
350
351 // ThreadManager calls this instead WrapCurrent() because
352 // ThreadManager::Instance() cannot be used while ThreadManager is
353 // being created.
354 // The method tries to get synchronization rights of the thread on Windows if
355 // |need_synchronize_access| is true.
356 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
357 bool need_synchronize_access);
358
Tommi51492422017-12-04 15:18:23 +0100359 // Return true if the thread is currently running.
360 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200361
362 // Processes received "Send" requests. If |source| is not null, only requests
363 // from |source| are processed, otherwise, all requests are processed.
364 void ReceiveSendsFromThread(const Thread* source);
365
366 // If |source| is not null, pops the first "Send" message from |source| in
367 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
368 // The caller must lock |crit_| before calling.
369 // Returns true if there is such a message.
370 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
371
372 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
373
374 std::list<_SendMessage> sendlist_;
375 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100376
Jonas Olssona4d87372019-07-05 19:08:33 +0200377 // TODO(tommi): Add thread checks for proper use of control methods.
378 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200379
380#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100381 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200382#endif
383
384#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100385 HANDLE thread_ = nullptr;
386 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200387#endif
388
Tommi51492422017-12-04 15:18:23 +0100389 // Indicates whether or not ownership of the worker thread lies with
390 // this instance or not. (i.e. owned_ == !wrapped).
391 // Must only be modified when the worker thread is not running.
392 bool owned_ = true;
393
394 // Only touched from the worker thread itself.
395 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200396
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100397 // Runs webrtc::QueuedTask posted to the Thread.
398 QueuedTaskHandler queued_task_handler_;
399
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200400 friend class ThreadManager;
401
402 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
403};
404
405// AutoThread automatically installs itself at construction
406// uninstalls at destruction, if a Thread object is
407// _not already_ associated with the current OS thread.
408
409class AutoThread : public Thread {
410 public:
411 AutoThread();
412 ~AutoThread() override;
413
414 private:
415 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
416};
417
418// AutoSocketServerThread automatically installs itself at
419// construction and uninstalls at destruction. If a Thread object is
420// already associated with the current OS thread, it is temporarily
421// disassociated and restored by the destructor.
422
423class AutoSocketServerThread : public Thread {
424 public:
425 explicit AutoSocketServerThread(SocketServer* ss);
426 ~AutoSocketServerThread() override;
427
428 private:
429 rtc::Thread* old_thread_;
430
431 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
432};
433
434} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200436#endif // RTC_BASE_THREAD_H_