blob: fb40a54b805e397017a27140776dd9866ce046a1 [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 Chapovalov89313452019-11-29 12:56:43 +010024#include "api/function_view.h"
Danil Chapovalov912b3b82019-11-22 15:52:40 +010025#include "api/task_queue/queued_task.h"
26#include "api/task_queue/task_queue_base.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/constructor_magic.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/message_handler.h"
30#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020033#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020034#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020035
36#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020038#endif
39
40namespace rtc {
41
42class Thread;
43
Henrik Boströmba4dcc32019-02-28 09:34:06 +010044namespace rtc_thread_internal {
45
Niels Möllerf13a0962019-05-17 10:15:06 +020046class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010047 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020048 virtual void Run() = 0;
49};
50
51template <class FunctorT>
52class MessageWithFunctor final : public MessageLikeTask {
53 public:
54 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010055 : functor_(std::forward<FunctorT>(functor)) {}
56
Niels Möllerf13a0962019-05-17 10:15:06 +020057 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010058
59 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020060 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010061
62 typename std::remove_reference<FunctorT>::type functor_;
63
Niels Möllerf13a0962019-05-17 10:15:06 +020064 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
65};
66
Henrik Boströmba4dcc32019-02-28 09:34:06 +010067} // namespace rtc_thread_internal
68
Mirko Bonadei35214fc2019-09-23 14:54:28 +020069class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020070 public:
71 static const int kForever = -1;
72
73 // Singleton, constructor and destructor are private.
74 static ThreadManager* Instance();
75
76 Thread* CurrentThread();
77 void SetCurrentThread(Thread* thread);
78
79 // Returns a thread object with its thread_ ivar set
80 // to whatever the OS uses to represent the thread.
81 // If there already *is* a Thread object corresponding to this thread,
82 // this method will return that. Otherwise it creates a new Thread
83 // object whose wrapped() method will return true, and whose
84 // handle will, on Win32, be opened with only synchronization privileges -
85 // if you need more privilegs, rather than changing this method, please
86 // write additional code to adjust the privileges, or call a different
87 // factory method of your own devising, because this one gets used in
88 // unexpected contexts (like inside browser plugins) and it would be a
89 // shame to break it. It is also conceivable on Win32 that we won't even
90 // be able to get synchronization privileges, in which case the result
91 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +020092 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020093 void UnwrapCurrentThread();
94
Niels Moller9d1840c2019-05-21 07:26:37 +000095 bool IsMainThread();
96
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020097 private:
98 ThreadManager();
99 ~ThreadManager();
100
101#if defined(WEBRTC_POSIX)
102 pthread_key_t key_;
103#endif
104
105#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100106 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200107#endif
108
Niels Moller9d1840c2019-05-21 07:26:37 +0000109 // The thread to potentially autowrap.
110 const PlatformThreadRef main_thread_ref_;
111
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200112 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
113};
114
115struct _SendMessage {
116 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200117 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200118 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200119 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200120};
121
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
123
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100124class RTC_LOCKABLE RTC_EXPORT Thread : public MessageQueue,
125 public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700126 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127 explicit Thread(SocketServer* ss);
128 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800129 // Constructors meant for subclasses; they should call DoInit themselves and
130 // pass false for |do_init|, so that DoInit is called only on the fully
131 // instantiated class, which avoids a vptr data race.
132 Thread(SocketServer* ss, bool do_init);
133 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134
135 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
136 // guarantee Stop() is explicitly called before the subclass is destroyed).
137 // This is required to avoid a data race between the destructor modifying the
138 // vtable, and the Thread::PreRun calling the virtual method Run().
139 ~Thread() override;
140
141 static std::unique_ptr<Thread> CreateWithSocketServer();
142 static std::unique_ptr<Thread> Create();
143 static Thread* Current();
144
145 // Used to catch performance regressions. Use this to disallow blocking calls
146 // (Invoke) for a given scope. If a synchronous call is made while this is in
147 // effect, an assert will be triggered.
148 // Note that this is a single threaded class.
149 class ScopedDisallowBlockingCalls {
150 public:
151 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100152 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
153 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
154 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200156
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200157 private:
158 Thread* const thread_;
159 const bool previous_state_;
160 };
161
162 bool IsCurrent() const;
163
164 // Sleeps the calling thread for the specified number of milliseconds, during
165 // which time no processing is performed. Returns false if sleeping was
166 // interrupted by a signal (POSIX only).
167 static bool SleepMs(int millis);
168
169 // Sets the thread's name, for debugging. Must be called before Start().
170 // If |obj| is non-null, its value is appended to |name|.
171 const std::string& name() const { return name_; }
172 bool SetName(const std::string& name, const void* obj);
173
174 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200175 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200176
177 // Tells the thread to stop and waits until it is joined.
178 // Never call Stop on the current thread. Instead use the inherited Quit
179 // function which will exit the base MessageQueue without terminating the
180 // underlying OS thread.
181 virtual void Stop();
182
183 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
184 // work, override Run(). To receive and dispatch messages, call
185 // ProcessMessages occasionally.
186 virtual void Run();
187
188 virtual void Send(const Location& posted_from,
189 MessageHandler* phandler,
190 uint32_t id = 0,
191 MessageData* pdata = nullptr);
192
193 // Convenience method to invoke a functor on another thread. Caller must
194 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
195 // Uses Send() internally, which blocks the current thread until execution
196 // is complete.
197 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
198 // &MyFunctionReturningBool);
199 // NOTE: This function can only be called when synchronous calls are allowed.
200 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100201 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
202 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100203 template <
204 class ReturnT,
205 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
206 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
207 ReturnT result;
208 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
209 return result;
210 }
211
212 template <
213 class ReturnT,
214 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
215 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
216 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 }
218
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100219 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
220 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200221 // is passed and (usually, see below) destroyed on |this| thread after it is
222 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100223 // Requirements of FunctorT:
224 // - FunctorT is movable.
225 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
226 // (if T is not void, the return value is discarded on |this| thread).
227 // - FunctorT has a public destructor that can be invoked from |this| thread
228 // after operation() has been invoked.
229 // - The functor must not cause the thread to quit before PostTask() is done.
230 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200231 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
232 // the task is run, it will be destroyed on |this| thread. However, if there
233 // are pending tasks by the time the Thread is destroyed, or a task is posted
234 // to a thread that is quitting, the task is destroyed immediately, on the
235 // calling thread. Destroying the Thread only blocks for any currently running
236 // task to complete. Note that TQ abstraction is even vaguer on how
237 // destruction happens in these cases, allowing destruction to happen
238 // asynchronously at a later time and on some arbitrary thread. So to ease
239 // migration, don't depend on Thread::PostTask destroying un-run tasks
240 // immediately.
241 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100242 // Example - Calling a class method:
243 // class Foo {
244 // public:
245 // void DoTheThing();
246 // };
247 // Foo foo;
248 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
249 //
250 // Example - Calling a lambda function:
251 // thread->PostTask(RTC_FROM_HERE,
252 // [&x, &y] { x.TrackComputations(y.Compute()); });
253 template <class FunctorT>
254 void PostTask(const Location& posted_from, FunctorT&& functor) {
Steve Antonbcc1a762019-12-11 11:21:53 -0800255 Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
Niels Möllerf13a0962019-05-17 10:15:06 +0200256 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100257 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100258 }
Steve Antonbcc1a762019-12-11 11:21:53 -0800259 template <class FunctorT>
260 void PostDelayedTask(const Location& posted_from,
261 FunctorT&& functor,
262 uint32_t milliseconds) {
263 PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
264 /*id=*/0,
265 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
266 std::forward<FunctorT>(functor)));
267 }
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100268
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 };
Steve Antonbcc1a762019-12-11 11:21:53 -0800341
Karl Wiberg32562252019-02-21 13:38:30 +0100342 // Sets the per-thread allow-blocking-calls flag and returns the previous
343 // value. Must be called on this thread.
344 bool SetAllowBlockingCalls(bool allow);
345
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200346#if defined(WEBRTC_WIN)
347 static DWORD WINAPI PreRun(LPVOID context);
348#else
Yves Gerey665174f2018-06-19 15:03:05 +0200349 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200350#endif
351
352 // ThreadManager calls this instead WrapCurrent() because
353 // ThreadManager::Instance() cannot be used while ThreadManager is
354 // being created.
355 // The method tries to get synchronization rights of the thread on Windows if
356 // |need_synchronize_access| is true.
357 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
358 bool need_synchronize_access);
359
Tommi51492422017-12-04 15:18:23 +0100360 // Return true if the thread is currently running.
361 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200362
363 // Processes received "Send" requests. If |source| is not null, only requests
364 // from |source| are processed, otherwise, all requests are processed.
365 void ReceiveSendsFromThread(const Thread* source);
366
367 // If |source| is not null, pops the first "Send" message from |source| in
368 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
369 // The caller must lock |crit_| before calling.
370 // Returns true if there is such a message.
371 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
372
Danil Chapovalov89313452019-11-29 12:56:43 +0100373 void InvokeInternal(const Location& posted_from,
374 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200375
Steve Antonbcc1a762019-12-11 11:21:53 -0800376 // Returns a static-lifetime MessageHandler which runs message with
377 // MessageLikeTask payload data.
378 static MessageHandler* GetPostTaskMessageHandler();
379
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200380 std::list<_SendMessage> sendlist_;
381 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100382
Jonas Olssona4d87372019-07-05 19:08:33 +0200383 // TODO(tommi): Add thread checks for proper use of control methods.
384 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200385
386#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100387 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200388#endif
389
390#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100391 HANDLE thread_ = nullptr;
392 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200393#endif
394
Tommi51492422017-12-04 15:18:23 +0100395 // Indicates whether or not ownership of the worker thread lies with
396 // this instance or not. (i.e. owned_ == !wrapped).
397 // Must only be modified when the worker thread is not running.
398 bool owned_ = true;
399
400 // Only touched from the worker thread itself.
401 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200402
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100403 // Runs webrtc::QueuedTask posted to the Thread.
404 QueuedTaskHandler queued_task_handler_;
405
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406 friend class ThreadManager;
407
408 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
409};
410
411// AutoThread automatically installs itself at construction
412// uninstalls at destruction, if a Thread object is
413// _not already_ associated with the current OS thread.
414
415class AutoThread : public Thread {
416 public:
417 AutoThread();
418 ~AutoThread() override;
419
420 private:
421 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
422};
423
424// AutoSocketServerThread automatically installs itself at
425// construction and uninstalls at destruction. If a Thread object is
426// already associated with the current OS thread, it is temporarily
427// disassociated and restored by the destructor.
428
429class AutoSocketServerThread : public Thread {
430 public:
431 explicit AutoSocketServerThread(SocketServer* ss);
432 ~AutoSocketServerThread() override;
433
434 private:
435 rtc::Thread* old_thread_;
436
437 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
438};
439
440} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000441
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200442#endif // RTC_BASE_THREAD_H_