blob: fde5e8bf3903dfe1940bcdbf0f6c46741cbe700b [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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <list>
15#include <memory>
16#include <string>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020018#if defined(WEBRTC_POSIX)
19#include <pthread.h>
20#endif
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/constructormagic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/messagequeue.h"
23#include "rtc_base/platform_thread_types.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024
25#if defined(WEBRTC_WIN)
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/win32.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020027#endif
28
29namespace rtc {
30
31class Thread;
32
33class ThreadManager {
34 public:
35 static const int kForever = -1;
36
37 // Singleton, constructor and destructor are private.
38 static ThreadManager* Instance();
39
40 Thread* CurrentThread();
41 void SetCurrentThread(Thread* thread);
42
43 // Returns a thread object with its thread_ ivar set
44 // to whatever the OS uses to represent the thread.
45 // If there already *is* a Thread object corresponding to this thread,
46 // this method will return that. Otherwise it creates a new Thread
47 // object whose wrapped() method will return true, and whose
48 // handle will, on Win32, be opened with only synchronization privileges -
49 // if you need more privilegs, rather than changing this method, please
50 // write additional code to adjust the privileges, or call a different
51 // factory method of your own devising, because this one gets used in
52 // unexpected contexts (like inside browser plugins) and it would be a
53 // shame to break it. It is also conceivable on Win32 that we won't even
54 // be able to get synchronization privileges, in which case the result
55 // will have a null handle.
Yves Gerey665174f2018-06-19 15:03:05 +020056 Thread* WrapCurrentThread();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020057 void UnwrapCurrentThread();
58
59 bool IsMainThread();
60
61 private:
62 ThreadManager();
63 ~ThreadManager();
64
65#if defined(WEBRTC_POSIX)
66 pthread_key_t key_;
67#endif
68
69#if defined(WEBRTC_WIN)
Tommi51492422017-12-04 15:18:23 +010070 const DWORD key_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071#endif
72
73 // The thread to potentially autowrap.
Tommi51492422017-12-04 15:18:23 +010074 const PlatformThreadRef main_thread_ref_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020075
76 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
77};
78
79struct _SendMessage {
80 _SendMessage() {}
Yves Gerey665174f2018-06-19 15:03:05 +020081 Thread* thread;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020082 Message msg;
Yves Gerey665174f2018-06-19 15:03:05 +020083 bool* ready;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020084};
85
86class Runnable {
87 public:
88 virtual ~Runnable() {}
89 virtual void Run(Thread* thread) = 0;
90
91 protected:
92 Runnable() {}
93
94 private:
95 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
96};
97
98// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
99
danilchap3c6abd22017-09-06 05:46:29 -0700100class RTC_LOCKABLE Thread : public MessageQueue {
tommia8a35152017-07-13 05:47:25 -0700101 public:
tommie7251592017-07-14 14:44:46 -0700102 // DEPRECATED.
103 // The default constructor should not be used because it hides whether or
104 // not a socket server will be associated with the thread. Most instances
105 // of Thread do actually not need one, so please use either of the Create*
106 // methods to construct an instance of Thread.
charujaina117b042017-07-13 07:06:39 -0700107 Thread();
tommie7251592017-07-14 14:44:46 -0700108
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200109 explicit Thread(SocketServer* ss);
110 explicit Thread(std::unique_ptr<SocketServer> ss);
Taylor Brandstetter08672602018-03-02 15:20:33 -0800111 // Constructors meant for subclasses; they should call DoInit themselves and
112 // pass false for |do_init|, so that DoInit is called only on the fully
113 // instantiated class, which avoids a vptr data race.
114 Thread(SocketServer* ss, bool do_init);
115 Thread(std::unique_ptr<SocketServer> ss, bool do_init);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200116
117 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
118 // guarantee Stop() is explicitly called before the subclass is destroyed).
119 // This is required to avoid a data race between the destructor modifying the
120 // vtable, and the Thread::PreRun calling the virtual method Run().
121 ~Thread() override;
122
123 static std::unique_ptr<Thread> CreateWithSocketServer();
124 static std::unique_ptr<Thread> Create();
125 static Thread* Current();
126
127 // Used to catch performance regressions. Use this to disallow blocking calls
128 // (Invoke) for a given scope. If a synchronous call is made while this is in
129 // effect, an assert will be triggered.
130 // Note that this is a single threaded class.
131 class ScopedDisallowBlockingCalls {
132 public:
133 ScopedDisallowBlockingCalls();
134 ~ScopedDisallowBlockingCalls();
Yves Gerey665174f2018-06-19 15:03:05 +0200135
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200136 private:
137 Thread* const thread_;
138 const bool previous_state_;
139 };
140
141 bool IsCurrent() const;
142
143 // Sleeps the calling thread for the specified number of milliseconds, during
144 // which time no processing is performed. Returns false if sleeping was
145 // interrupted by a signal (POSIX only).
146 static bool SleepMs(int millis);
147
148 // Sets the thread's name, for debugging. Must be called before Start().
149 // If |obj| is non-null, its value is appended to |name|.
150 const std::string& name() const { return name_; }
151 bool SetName(const std::string& name, const void* obj);
152
153 // Starts the execution of the thread.
154 bool Start(Runnable* runnable = nullptr);
155
156 // Tells the thread to stop and waits until it is joined.
157 // Never call Stop on the current thread. Instead use the inherited Quit
158 // function which will exit the base MessageQueue without terminating the
159 // underlying OS thread.
160 virtual void Stop();
161
162 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
163 // work, override Run(). To receive and dispatch messages, call
164 // ProcessMessages occasionally.
165 virtual void Run();
166
167 virtual void Send(const Location& posted_from,
168 MessageHandler* phandler,
169 uint32_t id = 0,
170 MessageData* pdata = nullptr);
171
172 // Convenience method to invoke a functor on another thread. Caller must
173 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
174 // Uses Send() internally, which blocks the current thread until execution
175 // is complete.
176 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
177 // &MyFunctionReturningBool);
178 // NOTE: This function can only be called when synchronous calls are allowed.
179 // See ScopedDisallowBlockingCalls for details.
180 template <class ReturnT, class FunctorT>
Karl Wibergd6b48192017-10-16 23:01:06 +0200181 ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {
182 FunctorMessageHandler<ReturnT, FunctorT> handler(
183 std::forward<FunctorT>(functor));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200184 InvokeInternal(posted_from, &handler);
185 return handler.MoveResult();
186 }
187
188 // From MessageQueue
Niels Möller8909a632018-09-06 08:42:44 +0200189 bool IsProcessingMessagesForTesting() override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200190 void Clear(MessageHandler* phandler,
191 uint32_t id = MQID_ANY,
192 MessageList* removed = nullptr) override;
193 void ReceiveSends() override;
194
195 // ProcessMessages will process I/O and dispatch messages until:
196 // 1) cms milliseconds have elapsed (returns true)
197 // 2) Stop() is called (returns false)
198 bool ProcessMessages(int cms);
199
200 // Returns true if this is a thread that we created using the standard
201 // constructor, false if it was created by a call to
202 // ThreadManager::WrapCurrentThread(). The main thread of an application
203 // is generally not owned, since the OS representation of the thread
204 // obviously exists before we can get to it.
205 // You cannot call Start on non-owned threads.
206 bool IsOwned();
207
Tommi51492422017-12-04 15:18:23 +0100208 // Expose private method IsRunning() for tests.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200209 //
210 // DANGER: this is a terrible public API. Most callers that might want to
211 // call this likely do not have enough control/knowledge of the Thread in
212 // question to guarantee that the returned value remains true for the duration
213 // of whatever code is conditionally executing because of the return value!
Tommi51492422017-12-04 15:18:23 +0100214 bool RunningForTest() { return IsRunning(); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215
216 // Sets the per-thread allow-blocking-calls flag and returns the previous
217 // value. Must be called on this thread.
218 bool SetAllowBlockingCalls(bool allow);
219
220 // These functions are public to avoid injecting test hooks. Don't call them
221 // outside of tests.
222 // This method should be called when thread is created using non standard
223 // method, like derived implementation of rtc::Thread and it can not be
224 // started by calling Start(). This will set started flag to true and
225 // owned to false. This must be called from the current thread.
226 bool WrapCurrent();
227 void UnwrapCurrent();
228
229 protected:
230 // Same as WrapCurrent except that it never fails as it does not try to
231 // acquire the synchronization access of the thread. The caller should never
232 // call Stop() or Join() on this thread.
233 void SafeWrapCurrent();
234
235 // Blocks the calling thread until this thread has terminated.
236 void Join();
237
238 static void AssertBlockingIsAllowedOnCurrentThread();
239
240 friend class ScopedDisallowBlockingCalls;
241
242 private:
243 struct ThreadInit {
244 Thread* thread;
245 Runnable* runnable;
246 };
247
248#if defined(WEBRTC_WIN)
249 static DWORD WINAPI PreRun(LPVOID context);
250#else
Yves Gerey665174f2018-06-19 15:03:05 +0200251 static void* PreRun(void* pv);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200252#endif
253
254 // ThreadManager calls this instead WrapCurrent() because
255 // ThreadManager::Instance() cannot be used while ThreadManager is
256 // being created.
257 // The method tries to get synchronization rights of the thread on Windows if
258 // |need_synchronize_access| is true.
259 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
260 bool need_synchronize_access);
261
Tommi51492422017-12-04 15:18:23 +0100262 // Return true if the thread is currently running.
263 bool IsRunning();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200264
265 // Processes received "Send" requests. If |source| is not null, only requests
266 // from |source| are processed, otherwise, all requests are processed.
267 void ReceiveSendsFromThread(const Thread* source);
268
269 // If |source| is not null, pops the first "Send" message from |source| in
270 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
271 // The caller must lock |crit_| before calling.
272 // Returns true if there is such a message.
273 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
274
275 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
276
277 std::list<_SendMessage> sendlist_;
278 std::string name_;
Tommi51492422017-12-04 15:18:23 +0100279
Yves Gerey665174f2018-06-19 15:03:05 +0200280// TODO(tommi): Add thread checks for proper use of control methods.
281// Ideally we should be able to just use PlatformThread.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200282
283#if defined(WEBRTC_POSIX)
Tommi6cea2b02017-12-04 18:51:16 +0100284 pthread_t thread_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200285#endif
286
287#if defined(WEBRTC_WIN)
Tommi6cea2b02017-12-04 18:51:16 +0100288 HANDLE thread_ = nullptr;
289 DWORD thread_id_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200290#endif
291
Tommi51492422017-12-04 15:18:23 +0100292 // Indicates whether or not ownership of the worker thread lies with
293 // this instance or not. (i.e. owned_ == !wrapped).
294 // Must only be modified when the worker thread is not running.
295 bool owned_ = true;
296
297 // Only touched from the worker thread itself.
298 bool blocking_calls_allowed_ = true;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200299
300 friend class ThreadManager;
301
302 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
303};
304
305// AutoThread automatically installs itself at construction
306// uninstalls at destruction, if a Thread object is
307// _not already_ associated with the current OS thread.
308
309class AutoThread : public Thread {
310 public:
311 AutoThread();
312 ~AutoThread() override;
313
314 private:
315 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
316};
317
318// AutoSocketServerThread automatically installs itself at
319// construction and uninstalls at destruction. If a Thread object is
320// already associated with the current OS thread, it is temporarily
321// disassociated and restored by the destructor.
322
323class AutoSocketServerThread : public Thread {
324 public:
325 explicit AutoSocketServerThread(SocketServer* ss);
326 ~AutoSocketServerThread() override;
327
328 private:
329 rtc::Thread* old_thread_;
330
331 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
332};
333
334} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200336#endif // RTC_BASE_THREAD_H_