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