blob: f433bab1ba29a76cab565fad20310da9dc09b1ea [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
67class MessageHandlerWithTask final : public MessageHandler {
68 public:
69 MessageHandlerWithTask() = default;
70
71 void OnMessage(Message* msg) override {
72 static_cast<MessageLikeTask*>(msg->pdata)->Run();
73 delete msg->pdata;
74 }
75
76 private:
77 ~MessageHandlerWithTask() override {}
78
79 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
Henrik Boströmba4dcc32019-02-28 09:34:06 +010080};
81
82} // namespace rtc_thread_internal
83
Mirko Bonadei35214fc2019-09-23 14:54:28 +020084class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020085 public:
86 static const int kForever = -1;
87
88 // Singleton, constructor and destructor are private.
89 static ThreadManager* Instance();
90
91 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
116#if defined(WEBRTC_POSIX)
117 pthread_key_t key_;
118#endif
119
120#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100121 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122#endif
123
Niels Moller9d1840c2019-05-21 07:26:37 +0000124 // The thread to potentially autowrap.
125 const PlatformThreadRef main_thread_ref_;
126
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
128};
129
130struct _SendMessage {
131 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200132 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200133 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200134 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200135};
136
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200137// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
138
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100139class RTC_LOCKABLE RTC_EXPORT Thread : public MessageQueue,
140 public webrtc::TaskQueueBase {
tommia8a35152017-07-13 05:47:25 -0700141 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200142 explicit Thread(SocketServer* ss);
143 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800144 // Constructors meant for subclasses; they should call DoInit themselves and
145 // pass false for |do_init|, so that DoInit is called only on the fully
146 // instantiated class, which avoids a vptr data race.
147 Thread(SocketServer* ss, bool do_init);
148 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200149
150 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
151 // guarantee Stop() is explicitly called before the subclass is destroyed).
152 // This is required to avoid a data race between the destructor modifying the
153 // vtable, and the Thread::PreRun calling the virtual method Run().
154 ~Thread() override;
155
156 static std::unique_ptr<Thread> CreateWithSocketServer();
157 static std::unique_ptr<Thread> Create();
158 static Thread* Current();
159
160 // Used to catch performance regressions. Use this to disallow blocking calls
161 // (Invoke) for a given scope. If a synchronous call is made while this is in
162 // effect, an assert will be triggered.
163 // Note that this is a single threaded class.
164 class ScopedDisallowBlockingCalls {
165 public:
166 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100167 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
168 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
169 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200171
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172 private:
173 Thread* const thread_;
174 const bool previous_state_;
175 };
176
177 bool IsCurrent() const;
178
179 // Sleeps the calling thread for the specified number of milliseconds, during
180 // which time no processing is performed. Returns false if sleeping was
181 // interrupted by a signal (POSIX only).
182 static bool SleepMs(int millis);
183
184 // Sets the thread's name, for debugging. Must be called before Start().
185 // If |obj| is non-null, its value is appended to |name|.
186 const std::string& name() const { return name_; }
187 bool SetName(const std::string& name, const void* obj);
188
189 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200190 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191
192 // Tells the thread to stop and waits until it is joined.
193 // Never call Stop on the current thread. Instead use the inherited Quit
194 // function which will exit the base MessageQueue without terminating the
195 // underlying OS thread.
196 virtual void Stop();
197
198 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
199 // work, override Run(). To receive and dispatch messages, call
200 // ProcessMessages occasionally.
201 virtual void Run();
202
203 virtual void Send(const Location& posted_from,
204 MessageHandler* phandler,
205 uint32_t id = 0,
206 MessageData* pdata = nullptr);
207
208 // Convenience method to invoke a functor on another thread. Caller must
209 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
210 // Uses Send() internally, which blocks the current thread until execution
211 // is complete.
212 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
213 // &MyFunctionReturningBool);
214 // NOTE: This function can only be called when synchronous calls are allowed.
215 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100216 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
217 // be achieved with PostTask() and callbacks instead.
Danil Chapovalov89313452019-11-29 12:56:43 +0100218 template <
219 class ReturnT,
220 typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
221 ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
222 ReturnT result;
223 InvokeInternal(posted_from, [functor, &result] { result = functor(); });
224 return result;
225 }
226
227 template <
228 class ReturnT,
229 typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
230 void Invoke(const Location& posted_from, FunctionView<void()> functor) {
231 InvokeInternal(posted_from, functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232 }
233
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100234 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
235 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200236 // is passed and (usually, see below) destroyed on |this| thread after it is
237 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100238 // Requirements of FunctorT:
239 // - FunctorT is movable.
240 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
241 // (if T is not void, the return value is discarded on |this| thread).
242 // - FunctorT has a public destructor that can be invoked from |this| thread
243 // after operation() has been invoked.
244 // - The functor must not cause the thread to quit before PostTask() is done.
245 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200246 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
247 // the task is run, it will be destroyed on |this| thread. However, if there
248 // are pending tasks by the time the Thread is destroyed, or a task is posted
249 // to a thread that is quitting, the task is destroyed immediately, on the
250 // calling thread. Destroying the Thread only blocks for any currently running
251 // task to complete. Note that TQ abstraction is even vaguer on how
252 // destruction happens in these cases, allowing destruction to happen
253 // asynchronously at a later time and on some arbitrary thread. So to ease
254 // migration, don't depend on Thread::PostTask destroying un-run tasks
255 // immediately.
256 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100257 // Example - Calling a class method:
258 // class Foo {
259 // public:
260 // void DoTheThing();
261 // };
262 // Foo foo;
263 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
264 //
265 // Example - Calling a lambda function:
266 // thread->PostTask(RTC_FROM_HERE,
267 // [&x, &y] { x.TrackComputations(y.Compute()); });
268 template <class FunctorT>
269 void PostTask(const Location& posted_from, FunctorT&& functor) {
Niels Möllerf13a0962019-05-17 10:15:06 +0200270 // Allocate at first call, never deallocate.
271 static auto* const handler =
272 new rtc_thread_internal::MessageHandlerWithTask;
273 Post(posted_from, handler, 0,
274 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100275 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100276 }
277
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100278 // From TaskQueueBase
279 void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
280 void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
281 uint32_t milliseconds) override;
282 void Delete() override;
283
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200284 // From MessageQueue
Niels Möller8909a632018-09-06 08:42:44 +0200285 bool IsProcessingMessagesForTesting() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200286 void Clear(MessageHandler* phandler,
287 uint32_t id = MQID_ANY,
288 MessageList* removed = nullptr) override;
289 void ReceiveSends() override;
290
291 // ProcessMessages will process I/O and dispatch messages until:
292 // 1) cms milliseconds have elapsed (returns true)
293 // 2) Stop() is called (returns false)
294 bool ProcessMessages(int cms);
295
296 // Returns true if this is a thread that we created using the standard
297 // constructor, false if it was created by a call to
298 // ThreadManager::WrapCurrentThread(). The main thread of an application
299 // is generally not owned, since the OS representation of the thread
300 // obviously exists before we can get to it.
301 // You cannot call Start on non-owned threads.
302 bool IsOwned();
303
Tommi51492422017-12-04 15:18:23 +0100304 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200305 //
306 // DANGER: this is a terrible public API. Most callers that might want to
307 // call this likely do not have enough control/knowledge of the Thread in
308 // question to guarantee that the returned value remains true for the duration
309 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100310 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200311
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200312 // These functions are public to avoid injecting test hooks. Don't call them
313 // outside of tests.
314 // This method should be called when thread is created using non standard
315 // method, like derived implementation of rtc::Thread and it can not be
316 // started by calling Start(). This will set started flag to true and
317 // owned to false. This must be called from the current thread.
318 bool WrapCurrent();
319 void UnwrapCurrent();
320
Karl Wiberg32562252019-02-21 13:38:30 +0100321 // Sets the per-thread allow-blocking-calls flag to false; this is
322 // irrevocable. Must be called on this thread.
323 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
324
325#ifdef WEBRTC_ANDROID
326 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
327 // invariants upheld by DisallowBlockingCalls() and
328 // ScopedDisallowBlockingCalls. Must be called on this thread.
329 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
330#endif
331
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200332 protected:
333 // Same as WrapCurrent except that it never fails as it does not try to
334 // acquire the synchronization access of the thread. The caller should never
335 // call Stop() or Join() on this thread.
336 void SafeWrapCurrent();
337
338 // Blocks the calling thread until this thread has terminated.
339 void Join();
340
341 static void AssertBlockingIsAllowedOnCurrentThread();
342
343 friend class ScopedDisallowBlockingCalls;
344
345 private:
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100346 class QueuedTaskHandler final : public MessageHandler {
347 public:
348 void OnMessage(Message* msg) override;
349 };
Karl Wiberg32562252019-02-21 13:38:30 +0100350 // Sets the per-thread allow-blocking-calls flag and returns the previous
351 // value. Must be called on this thread.
352 bool SetAllowBlockingCalls(bool allow);
353
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200354#if defined(WEBRTC_WIN)
355 static DWORD WINAPI PreRun(LPVOID context);
356#else
Yves Gerey665174f2018-06-19 15:03:05 +0200357 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200358#endif
359
360 // ThreadManager calls this instead WrapCurrent() because
361 // ThreadManager::Instance() cannot be used while ThreadManager is
362 // being created.
363 // The method tries to get synchronization rights of the thread on Windows if
364 // |need_synchronize_access| is true.
365 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
366 bool need_synchronize_access);
367
Tommi51492422017-12-04 15:18:23 +0100368 // Return true if the thread is currently running.
369 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200370
371 // Processes received "Send" requests. If |source| is not null, only requests
372 // from |source| are processed, otherwise, all requests are processed.
373 void ReceiveSendsFromThread(const Thread* source);
374
375 // If |source| is not null, pops the first "Send" message from |source| in
376 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
377 // The caller must lock |crit_| before calling.
378 // Returns true if there is such a message.
379 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
380
Danil Chapovalov89313452019-11-29 12:56:43 +0100381 void InvokeInternal(const Location& posted_from,
382 rtc::FunctionView<void()> functor);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200383
384 std::list<_SendMessage> sendlist_;
385 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100386
Jonas Olssona4d87372019-07-05 19:08:33 +0200387 // TODO(tommi): Add thread checks for proper use of control methods.
388 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200389
390#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100391 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200392#endif
393
394#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100395 HANDLE thread_ = nullptr;
396 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200397#endif
398
Tommi51492422017-12-04 15:18:23 +0100399 // Indicates whether or not ownership of the worker thread lies with
400 // this instance or not. (i.e. owned_ == !wrapped).
401 // Must only be modified when the worker thread is not running.
402 bool owned_ = true;
403
404 // Only touched from the worker thread itself.
405 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406
Danil Chapovalov912b3b82019-11-22 15:52:40 +0100407 // Runs webrtc::QueuedTask posted to the Thread.
408 QueuedTaskHandler queued_task_handler_;
409
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200410 friend class ThreadManager;
411
412 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
413};
414
415// AutoThread automatically installs itself at construction
416// uninstalls at destruction, if a Thread object is
417// _not already_ associated with the current OS thread.
418
419class AutoThread : public Thread {
420 public:
421 AutoThread();
422 ~AutoThread() override;
423
424 private:
425 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
426};
427
428// AutoSocketServerThread automatically installs itself at
429// construction and uninstalls at destruction. If a Thread object is
430// already associated with the current OS thread, it is temporarily
431// disassociated and restored by the destructor.
432
433class AutoSocketServerThread : public Thread {
434 public:
435 explicit AutoSocketServerThread(SocketServer* ss);
436 ~AutoSocketServerThread() override;
437
438 private:
439 rtc::Thread* old_thread_;
440
441 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
442};
443
444} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000445
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200446#endif // RTC_BASE_THREAD_H_