blob: 41052dfb1d7cfa40a6194ed75db810ac01a7d234 [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
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/constructor_magic.h"
Yves Gerey988cc082018-10-23 12:03:01 +020025#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/message_handler.h"
27#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/platform_thread_types.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020030#include "rtc_base/system/rtc_export.h"
Yves Gerey988cc082018-10-23 12:03:01 +020031#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020032
33#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020035#endif
36
37namespace rtc {
38
39class Thread;
40
Henrik Boströmba4dcc32019-02-28 09:34:06 +010041namespace rtc_thread_internal {
42
Niels Möllerf13a0962019-05-17 10:15:06 +020043class MessageLikeTask : public MessageData {
Henrik Boströmba4dcc32019-02-28 09:34:06 +010044 public:
Niels Möllerf13a0962019-05-17 10:15:06 +020045 virtual void Run() = 0;
46};
47
48template <class FunctorT>
49class MessageWithFunctor final : public MessageLikeTask {
50 public:
51 explicit MessageWithFunctor(FunctorT&& functor)
Henrik Boströmba4dcc32019-02-28 09:34:06 +010052 : functor_(std::forward<FunctorT>(functor)) {}
53
Niels Möllerf13a0962019-05-17 10:15:06 +020054 void Run() override { functor_(); }
Henrik Boströmba4dcc32019-02-28 09:34:06 +010055
56 private:
Niels Möllerf13a0962019-05-17 10:15:06 +020057 ~MessageWithFunctor() override {}
Henrik Boströmba4dcc32019-02-28 09:34:06 +010058
59 typename std::remove_reference<FunctorT>::type functor_;
60
Niels Möllerf13a0962019-05-17 10:15:06 +020061 RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
62};
63
64class MessageHandlerWithTask final : public MessageHandler {
65 public:
66 MessageHandlerWithTask() = default;
67
68 void OnMessage(Message* msg) override {
69 static_cast<MessageLikeTask*>(msg->pdata)->Run();
70 delete msg->pdata;
71 }
72
73 private:
74 ~MessageHandlerWithTask() override {}
75
76 RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
Henrik Boströmba4dcc32019-02-28 09:34:06 +010077};
78
79} // namespace rtc_thread_internal
80
Mirko Bonadei35214fc2019-09-23 14:54:28 +020081class RTC_EXPORT ThreadManager {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020082 public:
83 static const int kForever = -1;
84
85 // Singleton, constructor and destructor are private.
86 static ThreadManager* Instance();
87
88 Thread* CurrentThread();
89 void SetCurrentThread(Thread* thread);
90
91 // Returns a thread object with its thread_ ivar set
92 // to whatever the OS uses to represent the thread.
93 // If there already *is* a Thread object corresponding to this thread,
94 // this method will return that. Otherwise it creates a new Thread
95 // object whose wrapped() method will return true, and whose
96 // handle will, on Win32, be opened with only synchronization privileges -
97 // if you need more privilegs, rather than changing this method, please
98 // write additional code to adjust the privileges, or call a different
99 // factory method of your own devising, because this one gets used in
100 // unexpected contexts (like inside browser plugins) and it would be a
101 // shame to break it. It is also conceivable on Win32 that we won't even
102 // be able to get synchronization privileges, in which case the result
103 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +0200104 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200105 void UnwrapCurrentThread();
106
Niels Moller9d1840c2019-05-21 07:26:37 +0000107 bool IsMainThread();
108
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200109 private:
110 ThreadManager();
111 ~ThreadManager();
112
113#if defined(WEBRTC_POSIX)
114 pthread_key_t key_;
115#endif
116
117#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +0100118 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119#endif
120
Niels Moller9d1840c2019-05-21 07:26:37 +0000121 // The thread to potentially autowrap.
122 const PlatformThreadRef main_thread_ref_;
123
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
125};
126
127struct _SendMessage {
128 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +0200129 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200130 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +0200131 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200132};
133
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200134// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
135
Mirko Bonadei4ff1c872019-10-23 11:06:25 -0700136class RTC_LOCKABLE RTC_EXPORT Thread : public MessageQueue {
tommia8a35152017-07-13 05:47:25 -0700137 public:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200138 explicit Thread(SocketServer* ss);
139 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800140 // Constructors meant for subclasses; they should call DoInit themselves and
141 // pass false for |do_init|, so that DoInit is called only on the fully
142 // instantiated class, which avoids a vptr data race.
143 Thread(SocketServer* ss, bool do_init);
144 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145
146 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
147 // guarantee Stop() is explicitly called before the subclass is destroyed).
148 // This is required to avoid a data race between the destructor modifying the
149 // vtable, and the Thread::PreRun calling the virtual method Run().
150 ~Thread() override;
151
152 static std::unique_ptr<Thread> CreateWithSocketServer();
153 static std::unique_ptr<Thread> Create();
154 static Thread* Current();
155
156 // Used to catch performance regressions. Use this to disallow blocking calls
157 // (Invoke) for a given scope. If a synchronous call is made while this is in
158 // effect, an assert will be triggered.
159 // Note that this is a single threaded class.
160 class ScopedDisallowBlockingCalls {
161 public:
162 ScopedDisallowBlockingCalls();
Sebastian Jansson9debe5a2019-03-22 15:42:38 +0100163 ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
164 ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
165 delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200167
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200168 private:
169 Thread* const thread_;
170 const bool previous_state_;
171 };
172
173 bool IsCurrent() const;
174
175 // Sleeps the calling thread for the specified number of milliseconds, during
176 // which time no processing is performed. Returns false if sleeping was
177 // interrupted by a signal (POSIX only).
178 static bool SleepMs(int millis);
179
180 // Sets the thread's name, for debugging. Must be called before Start().
181 // If |obj| is non-null, its value is appended to |name|.
182 const std::string& name() const { return name_; }
183 bool SetName(const std::string& name, const void* obj);
184
185 // Starts the execution of the thread.
Niels Möllerd2e50132019-06-11 09:24:14 +0200186 bool Start();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200187
188 // Tells the thread to stop and waits until it is joined.
189 // Never call Stop on the current thread. Instead use the inherited Quit
190 // function which will exit the base MessageQueue without terminating the
191 // underlying OS thread.
192 virtual void Stop();
193
194 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
195 // work, override Run(). To receive and dispatch messages, call
196 // ProcessMessages occasionally.
197 virtual void Run();
198
199 virtual void Send(const Location& posted_from,
200 MessageHandler* phandler,
201 uint32_t id = 0,
202 MessageData* pdata = nullptr);
203
204 // Convenience method to invoke a functor on another thread. Caller must
205 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
206 // Uses Send() internally, which blocks the current thread until execution
207 // is complete.
208 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
209 // &MyFunctionReturningBool);
210 // NOTE: This function can only be called when synchronous calls are allowed.
211 // See ScopedDisallowBlockingCalls for details.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100212 // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
213 // be achieved with PostTask() and callbacks instead.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200214 template <class ReturnT, class FunctorT>
Karl Wibergd6b48192017-10-16 23:01:06 +0200215 ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {
216 FunctorMessageHandler<ReturnT, FunctorT> handler(
217 std::forward<FunctorT>(functor));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200218 InvokeInternal(posted_from, &handler);
219 return handler.MoveResult();
220 }
221
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100222 // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
223 // without blocking the thread that invoked PostTask(). Ownership of |functor|
Niels Möllerf13a0962019-05-17 10:15:06 +0200224 // is passed and (usually, see below) destroyed on |this| thread after it is
225 // invoked.
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100226 // Requirements of FunctorT:
227 // - FunctorT is movable.
228 // - FunctorT implements "T operator()()" or "T operator()() const" for some T
229 // (if T is not void, the return value is discarded on |this| thread).
230 // - FunctorT has a public destructor that can be invoked from |this| thread
231 // after operation() has been invoked.
232 // - The functor must not cause the thread to quit before PostTask() is done.
233 //
Niels Möllerf13a0962019-05-17 10:15:06 +0200234 // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
235 // the task is run, it will be destroyed on |this| thread. However, if there
236 // are pending tasks by the time the Thread is destroyed, or a task is posted
237 // to a thread that is quitting, the task is destroyed immediately, on the
238 // calling thread. Destroying the Thread only blocks for any currently running
239 // task to complete. Note that TQ abstraction is even vaguer on how
240 // destruction happens in these cases, allowing destruction to happen
241 // asynchronously at a later time and on some arbitrary thread. So to ease
242 // migration, don't depend on Thread::PostTask destroying un-run tasks
243 // immediately.
244 //
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100245 // Example - Calling a class method:
246 // class Foo {
247 // public:
248 // void DoTheThing();
249 // };
250 // Foo foo;
251 // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
252 //
253 // Example - Calling a lambda function:
254 // thread->PostTask(RTC_FROM_HERE,
255 // [&x, &y] { x.TrackComputations(y.Compute()); });
256 template <class FunctorT>
257 void PostTask(const Location& posted_from, FunctorT&& functor) {
Niels Möllerf13a0962019-05-17 10:15:06 +0200258 // Allocate at first call, never deallocate.
259 static auto* const handler =
260 new rtc_thread_internal::MessageHandlerWithTask;
261 Post(posted_from, handler, 0,
262 new rtc_thread_internal::MessageWithFunctor<FunctorT>(
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100263 std::forward<FunctorT>(functor)));
Henrik Boströmba4dcc32019-02-28 09:34:06 +0100264 }
265
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200266 // From MessageQueue
Niels Möller8909a632018-09-06 08:42:44 +0200267 bool IsProcessingMessagesForTesting() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200268 void Clear(MessageHandler* phandler,
269 uint32_t id = MQID_ANY,
270 MessageList* removed = nullptr) override;
271 void ReceiveSends() override;
272
273 // ProcessMessages will process I/O and dispatch messages until:
274 // 1) cms milliseconds have elapsed (returns true)
275 // 2) Stop() is called (returns false)
276 bool ProcessMessages(int cms);
277
278 // Returns true if this is a thread that we created using the standard
279 // constructor, false if it was created by a call to
280 // ThreadManager::WrapCurrentThread(). The main thread of an application
281 // is generally not owned, since the OS representation of the thread
282 // obviously exists before we can get to it.
283 // You cannot call Start on non-owned threads.
284 bool IsOwned();
285
Tommi51492422017-12-04 15:18:23 +0100286 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200287 //
288 // DANGER: this is a terrible public API. Most callers that might want to
289 // call this likely do not have enough control/knowledge of the Thread in
290 // question to guarantee that the returned value remains true for the duration
291 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100292 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200294 // These functions are public to avoid injecting test hooks. Don't call them
295 // outside of tests.
296 // This method should be called when thread is created using non standard
297 // method, like derived implementation of rtc::Thread and it can not be
298 // started by calling Start(). This will set started flag to true and
299 // owned to false. This must be called from the current thread.
300 bool WrapCurrent();
301 void UnwrapCurrent();
302
Karl Wiberg32562252019-02-21 13:38:30 +0100303 // Sets the per-thread allow-blocking-calls flag to false; this is
304 // irrevocable. Must be called on this thread.
305 void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
306
307#ifdef WEBRTC_ANDROID
308 // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
309 // invariants upheld by DisallowBlockingCalls() and
310 // ScopedDisallowBlockingCalls. Must be called on this thread.
311 void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
312#endif
313
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200314 protected:
315 // Same as WrapCurrent except that it never fails as it does not try to
316 // acquire the synchronization access of the thread. The caller should never
317 // call Stop() or Join() on this thread.
318 void SafeWrapCurrent();
319
320 // Blocks the calling thread until this thread has terminated.
321 void Join();
322
323 static void AssertBlockingIsAllowedOnCurrentThread();
324
325 friend class ScopedDisallowBlockingCalls;
326
327 private:
Karl Wiberg32562252019-02-21 13:38:30 +0100328 // Sets the per-thread allow-blocking-calls flag and returns the previous
329 // value. Must be called on this thread.
330 bool SetAllowBlockingCalls(bool allow);
331
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200332#if defined(WEBRTC_WIN)
333 static DWORD WINAPI PreRun(LPVOID context);
334#else
Yves Gerey665174f2018-06-19 15:03:05 +0200335 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200336#endif
337
338 // ThreadManager calls this instead WrapCurrent() because
339 // ThreadManager::Instance() cannot be used while ThreadManager is
340 // being created.
341 // The method tries to get synchronization rights of the thread on Windows if
342 // |need_synchronize_access| is true.
343 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
344 bool need_synchronize_access);
345
Tommi51492422017-12-04 15:18:23 +0100346 // Return true if the thread is currently running.
347 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200348
349 // Processes received "Send" requests. If |source| is not null, only requests
350 // from |source| are processed, otherwise, all requests are processed.
351 void ReceiveSendsFromThread(const Thread* source);
352
353 // If |source| is not null, pops the first "Send" message from |source| in
354 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
355 // The caller must lock |crit_| before calling.
356 // Returns true if there is such a message.
357 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
358
359 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
360
361 std::list<_SendMessage> sendlist_;
362 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100363
Jonas Olssona4d87372019-07-05 19:08:33 +0200364 // TODO(tommi): Add thread checks for proper use of control methods.
365 // Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200366
367#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100368 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200369#endif
370
371#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100372 HANDLE thread_ = nullptr;
373 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200374#endif
375
Tommi51492422017-12-04 15:18:23 +0100376 // Indicates whether or not ownership of the worker thread lies with
377 // this instance or not. (i.e. owned_ == !wrapped).
378 // Must only be modified when the worker thread is not running.
379 bool owned_ = true;
380
381 // Only touched from the worker thread itself.
382 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200383
384 friend class ThreadManager;
385
386 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
387};
388
389// AutoThread automatically installs itself at construction
390// uninstalls at destruction, if a Thread object is
391// _not already_ associated with the current OS thread.
392
393class AutoThread : public Thread {
394 public:
395 AutoThread();
396 ~AutoThread() override;
397
398 private:
399 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
400};
401
402// AutoSocketServerThread automatically installs itself at
403// construction and uninstalls at destruction. If a Thread object is
404// already associated with the current OS thread, it is temporarily
405// disassociated and restored by the destructor.
406
407class AutoSocketServerThread : public Thread {
408 public:
409 explicit AutoSocketServerThread(SocketServer* ss);
410 ~AutoSocketServerThread() override;
411
412 private:
413 rtc::Thread* old_thread_;
414
415 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
416};
417
418} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000419
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200420#endif // RTC_BASE_THREAD_H_