blob: 2b4d0203ba2fe547bf7f997472cf813831fbc106 [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>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020015#include <list>
16#include <memory>
17#include <string>
Yves Gerey988cc082018-10-23 12:03:01 +020018#include <type_traits>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020020#if defined(WEBRTC_POSIX)
21#include <pthread.h>
22#endif
Steve Anton10542f22019-01-11 09:11:00 -080023#include "rtc_base/constructor_magic.h"
Yves Gerey988cc082018-10-23 12:03:01 +020024#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "rtc_base/message_handler.h"
26#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "rtc_base/socket_server.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020030
31#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020033#endif
34
35namespace rtc {
36
37class Thread;
38
Henrik Boströmba4dcc32019-02-28 09:34:06 +010039namespace rtc_thread_internal {
40
Niels Möllerf13a0962019-05-17 10:15:06 +020041class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010042 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020043 virtual void Run() = 0;
44};
45
46template <class FunctorT>
47class MessageWithFunctor final : public MessageLikeTask {
48 public:
49 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010050 : functor_(std::forward<FunctorT>(functor)) {}
51
Niels Möllerf13a0962019-05-17 10:15:06 +020052 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010053
54 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020055 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010056
57 typename std::remove_reference<FunctorT>::type functor_;
58
Niels Möllerf13a0962019-05-17 10:15:06 +020059 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
60};
61
62class MessageHandlerWithTask final : public MessageHandler {
63 public:
64 MessageHandlerWithTask() = default;
65
66 void OnMessage(Message* msg) override {
67 static_cast<MessageLikeTask*>(msg->pdata)->Run();
68 delete msg->pdata;
69 }
70
71 private:
72 ~MessageHandlerWithTask() override {}
73
74 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
Henrik Boströmba4dcc32019-02-28 09:34:06 +010075};
76
77} // namespace rtc_thread_internal
78
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020079class ThreadManager {
80 public:
81 static const int kForever = -1;
82
83 // Singleton, constructor and destructor are private.
84 static ThreadManager* Instance();
85
86 Thread* CurrentThread();
87 void SetCurrentThread(Thread* thread);
88
89 // Returns a thread object with its thread_ ivar set
90 // to whatever the OS uses to represent the thread.
91 // If there already *is* a Thread object corresponding to this thread,
92 // this method will return that. Otherwise it creates a new Thread
93 // object whose wrapped() method will return true, and whose
94 // handle will, on Win32, be opened with only synchronization privileges -
95 // if you need more privilegs, rather than changing this method, please
96 // write additional code to adjust the privileges, or call a different
97 // factory method of your own devising, because this one gets used in
98 // unexpected contexts (like inside browser plugins) and it would be a
99 // shame to break it. It is also conceivable on Win32 that we won't even
100 // be able to get synchronization privileges, in which case the result
101 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200102 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200103 void UnwrapCurrentThread();
104
Niels Moller9d1840c2019-05-21 07:26:37 +0000105 bool IsMainThread();
106
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200107 private:
108 ThreadManager();
109 ~ThreadManager();
110
111#if defined(WEBRTC_POSIX)
112 pthread_key_t key_;
113#endif
114
115#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100116 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200117#endif
118
Niels Moller9d1840c2019-05-21 07:26:37 +0000119 // The thread to potentially autowrap.
120 const PlatformThreadRef main_thread_ref_;
121
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
123};
124
125struct _SendMessage {
126 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200127 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200128 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200129 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200130};
131
132class Runnable {
133 public:
134 virtual ~Runnable() {}
135 virtual void Run(Thread* thread) = 0;
136
137 protected:
138 Runnable() {}
139
140 private:
141 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
142};
143
144// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
145
danilchap3c6abd22017-09-06 05:46:29 -0700146class RTC_LOCKABLE Thread : public MessageQueue {
tommia8a35152017-07-13 05:47:25 -0700147 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148 explicit Thread(SocketServer* ss);
149 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800150 // Constructors meant for subclasses; they should call DoInit themselves and
151 // pass false for |do_init|, so that DoInit is called only on the fully
152 // instantiated class, which avoids a vptr data race.
153 Thread(SocketServer* ss, bool do_init);
154 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200155
156 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
157 // guarantee Stop() is explicitly called before the subclass is destroyed).
158 // This is required to avoid a data race between the destructor modifying the
159 // vtable, and the Thread::PreRun calling the virtual method Run().
160 ~Thread() override;
161
162 static std::unique_ptr<Thread> CreateWithSocketServer();
163 static std::unique_ptr<Thread> Create();
164 static Thread* Current();
165
166 // Used to catch performance regressions. Use this to disallow blocking calls
167 // (Invoke) for a given scope. If a synchronous call is made while this is in
168 // effect, an assert will be triggered.
169 // Note that this is a single threaded class.
170 class ScopedDisallowBlockingCalls {
171 public:
172 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100173 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
174 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
175 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200176 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200177
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200178 private:
179 Thread* const thread_;
180 const bool previous_state_;
181 };
182
183 bool IsCurrent() const;
184
185 // Sleeps the calling thread for the specified number of milliseconds, during
186 // which time no processing is performed. Returns false if sleeping was
187 // interrupted by a signal (POSIX only).
188 static bool SleepMs(int millis);
189
190 // Sets the thread's name, for debugging. Must be called before Start().
191 // If |obj| is non-null, its value is appended to |name|.
192 const std::string& name() const { return name_; }
193 bool SetName(const std::string& name, const void* obj);
194
195 // Starts the execution of the thread.
196 bool Start(Runnable* runnable = nullptr);
197
198 // Tells the thread to stop and waits until it is joined.
199 // Never call Stop on the current thread. Instead use the inherited Quit
200 // function which will exit the base MessageQueue without terminating the
201 // underlying OS thread.
202 virtual void Stop();
203
204 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
205 // work, override Run(). To receive and dispatch messages, call
206 // ProcessMessages occasionally.
207 virtual void Run();
208
209 virtual void Send(const Location& posted_from,
210 MessageHandler* phandler,
211 uint32_t id = 0,
212 MessageData* pdata = nullptr);
213
214 // Convenience method to invoke a functor on another thread. Caller must
215 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
216 // Uses Send() internally, which blocks the current thread until execution
217 // is complete.
218 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
219 // &MyFunctionReturningBool);
220 // NOTE: This function can only be called when synchronous calls are allowed.
221 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100222 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
223 // be achieved with PostTask() and callbacks instead.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200224 template <class ReturnT, class FunctorT>
Karl Wibergd6b48192017-10-16 23:01:06 +0200225 ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {
226 FunctorMessageHandler<ReturnT, FunctorT> handler(
227 std::forward<FunctorT>(functor));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200228 InvokeInternal(posted_from, &handler);
229 return handler.MoveResult();
230 }
231
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100232 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
233 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200234 // is passed and (usually, see below) destroyed on |this| thread after it is
235 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100236 // Requirements of FunctorT:
237 // - FunctorT is movable.
238 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
239 // (if T is not void, the return value is discarded on |this| thread).
240 // - FunctorT has a public destructor that can be invoked from |this| thread
241 // after operation() has been invoked.
242 // - The functor must not cause the thread to quit before PostTask() is done.
243 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200244 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
245 // the task is run, it will be destroyed on |this| thread. However, if there
246 // are pending tasks by the time the Thread is destroyed, or a task is posted
247 // to a thread that is quitting, the task is destroyed immediately, on the
248 // calling thread. Destroying the Thread only blocks for any currently running
249 // task to complete. Note that TQ abstraction is even vaguer on how
250 // destruction happens in these cases, allowing destruction to happen
251 // asynchronously at a later time and on some arbitrary thread. So to ease
252 // migration, don't depend on Thread::PostTask destroying un-run tasks
253 // immediately.
254 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100255 // Example - Calling a class method:
256 // class Foo {
257 // public:
258 // void DoTheThing();
259 // };
260 // Foo foo;
261 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
262 //
263 // Example - Calling a lambda function:
264 // thread->PostTask(RTC_FROM_HERE,
265 // [&x, &y] { x.TrackComputations(y.Compute()); });
266 template <class FunctorT>
267 void PostTask(const Location& posted_from, FunctorT&& functor) {
Niels Möllerf13a0962019-05-17 10:15:06 +0200268 // Allocate at first call, never deallocate.
269 static auto* const handler =
270 new rtc_thread_internal::MessageHandlerWithTask;
271 Post(posted_from, handler, 0,
272 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100273 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100274 }
275
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200276 // From MessageQueue
Niels Möller8909a632018-09-06 08:42:44 +0200277 bool IsProcessingMessagesForTesting() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200278 void Clear(MessageHandler* phandler,
279 uint32_t id = MQID_ANY,
280 MessageList* removed = nullptr) override;
281 void ReceiveSends() override;
282
283 // ProcessMessages will process I/O and dispatch messages until:
284 // 1) cms milliseconds have elapsed (returns true)
285 // 2) Stop() is called (returns false)
286 bool ProcessMessages(int cms);
287
288 // Returns true if this is a thread that we created using the standard
289 // constructor, false if it was created by a call to
290 // ThreadManager::WrapCurrentThread(). The main thread of an application
291 // is generally not owned, since the OS representation of the thread
292 // obviously exists before we can get to it.
293 // You cannot call Start on non-owned threads.
294 bool IsOwned();
295
Tommi51492422017-12-04 15:18:23 +0100296 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200297 //
298 // DANGER: this is a terrible public API. Most callers that might want to
299 // call this likely do not have enough control/knowledge of the Thread in
300 // question to guarantee that the returned value remains true for the duration
301 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100302 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200303
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200304 // These functions are public to avoid injecting test hooks. Don't call them
305 // outside of tests.
306 // This method should be called when thread is created using non standard
307 // method, like derived implementation of rtc::Thread and it can not be
308 // started by calling Start(). This will set started flag to true and
309 // owned to false. This must be called from the current thread.
310 bool WrapCurrent();
311 void UnwrapCurrent();
312
Karl Wiberg32562252019-02-21 13:38:30 +0100313 // Sets the per-thread allow-blocking-calls flag to false; this is
314 // irrevocable. Must be called on this thread.
315 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
316
317#ifdef WEBRTC_ANDROID
318 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
319 // invariants upheld by DisallowBlockingCalls() and
320 // ScopedDisallowBlockingCalls. Must be called on this thread.
321 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
322#endif
323
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200324 protected:
325 // Same as WrapCurrent except that it never fails as it does not try to
326 // acquire the synchronization access of the thread. The caller should never
327 // call Stop() or Join() on this thread.
328 void SafeWrapCurrent();
329
330 // Blocks the calling thread until this thread has terminated.
331 void Join();
332
333 static void AssertBlockingIsAllowedOnCurrentThread();
334
335 friend class ScopedDisallowBlockingCalls;
336
337 private:
338 struct ThreadInit {
339 Thread* thread;
340 Runnable* runnable;
341 };
342
Karl Wiberg32562252019-02-21 13:38:30 +0100343 // Sets the per-thread allow-blocking-calls flag and returns the previous
344 // value. Must be called on this thread.
345 bool SetAllowBlockingCalls(bool allow);
346
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200347#if defined(WEBRTC_WIN)
348 static DWORD WINAPI PreRun(LPVOID context);
349#else
Yves Gerey665174f2018-06-19 15:03:05 +0200350 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200351#endif
352
353 // ThreadManager calls this instead WrapCurrent() because
354 // ThreadManager::Instance() cannot be used while ThreadManager is
355 // being created.
356 // The method tries to get synchronization rights of the thread on Windows if
357 // |need_synchronize_access| is true.
358 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
359 bool need_synchronize_access);
360
Tommi51492422017-12-04 15:18:23 +0100361 // Return true if the thread is currently running.
362 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200363
364 // Processes received "Send" requests. If |source| is not null, only requests
365 // from |source| are processed, otherwise, all requests are processed.
366 void ReceiveSendsFromThread(const Thread* source);
367
368 // If |source| is not null, pops the first "Send" message from |source| in
369 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
370 // The caller must lock |crit_| before calling.
371 // Returns true if there is such a message.
372 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
373
374 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
375
376 std::list<_SendMessage> sendlist_;
377 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100378
Yves Gerey665174f2018-06-19 15:03:05 +0200379// TODO(tommi): Add thread checks for proper use of control methods.
380// Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200381
382#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100383 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200384#endif
385
386#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100387 HANDLE thread_ = nullptr;
388 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200389#endif
390
Tommi51492422017-12-04 15:18:23 +0100391 // Indicates whether or not ownership of the worker thread lies with
392 // this instance or not. (i.e. owned_ == !wrapped).
393 // Must only be modified when the worker thread is not running.
394 bool owned_ = true;
395
396 // Only touched from the worker thread itself.
397 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200398
399 friend class ThreadManager;
400
401 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
402};
403
404// AutoThread automatically installs itself at construction
405// uninstalls at destruction, if a Thread object is
406// _not already_ associated with the current OS thread.
407
408class AutoThread : public Thread {
409 public:
410 AutoThread();
411 ~AutoThread() override;
412
413 private:
414 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
415};
416
417// AutoSocketServerThread automatically installs itself at
418// construction and uninstalls at destruction. If a Thread object is
419// already associated with the current OS thread, it is temporarily
420// disassociated and restored by the destructor.
421
422class AutoSocketServerThread : public Thread {
423 public:
424 explicit AutoSocketServerThread(SocketServer* ss);
425 ~AutoSocketServerThread() override;
426
427 private:
428 rtc::Thread* old_thread_;
429
430 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
431};
432
433} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200435#endif // RTC_BASE_THREAD_H_