blob: d9dbb0b0b9720429824a5b31243b70683304f64f [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
11#ifndef WEBRTC_BASE_THREAD_H_
12#define WEBRTC_BASE_THREAD_H_
13
14#include <algorithm>
15#include <list>
16#include <string>
17#include <vector>
18
19#if defined(WEBRTC_POSIX)
20#include <pthread.h>
21#endif
22#include "webrtc/base/constructormagic.h"
fischman@webrtc.orge5063b12014-05-23 17:28:50 +000023#include "webrtc/base/event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000024#include "webrtc/base/messagequeue.h"
25
26#if defined(WEBRTC_WIN)
27#include "webrtc/base/win32.h"
28#endif
29
30namespace rtc {
31
32class Thread;
33
34class ThreadManager {
35 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +000036 static const int kForever = -1;
37
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038 ThreadManager();
39 ~ThreadManager();
40
41 static ThreadManager* Instance();
42
43 Thread* CurrentThread();
44 void SetCurrentThread(Thread* thread);
45
46 // Returns a thread object with its thread_ ivar set
47 // to whatever the OS uses to represent the thread.
48 // If there already *is* a Thread object corresponding to this thread,
49 // this method will return that. Otherwise it creates a new Thread
50 // object whose wrapped() method will return true, and whose
51 // handle will, on Win32, be opened with only synchronization privileges -
52 // if you need more privilegs, rather than changing this method, please
53 // write additional code to adjust the privileges, or call a different
54 // factory method of your own devising, because this one gets used in
55 // unexpected contexts (like inside browser plugins) and it would be a
56 // shame to break it. It is also conceivable on Win32 that we won't even
57 // be able to get synchronization privileges, in which case the result
58 // will have a NULL handle.
59 Thread *WrapCurrentThread();
60 void UnwrapCurrentThread();
61
62 private:
63#if defined(WEBRTC_POSIX)
64 pthread_key_t key_;
65#endif
66
67#if defined(WEBRTC_WIN)
68 DWORD key_;
69#endif
70
71 DISALLOW_COPY_AND_ASSIGN(ThreadManager);
72};
73
74struct _SendMessage {
75 _SendMessage() {}
76 Thread *thread;
77 Message msg;
78 bool *ready;
79};
80
81enum ThreadPriority {
82 PRIORITY_IDLE = -1,
83 PRIORITY_NORMAL = 0,
84 PRIORITY_ABOVE_NORMAL = 1,
85 PRIORITY_HIGH = 2,
86};
87
88class Runnable {
89 public:
90 virtual ~Runnable() {}
91 virtual void Run(Thread* thread) = 0;
92
93 protected:
94 Runnable() {}
95
96 private:
97 DISALLOW_COPY_AND_ASSIGN(Runnable);
98};
99
100// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
101
102class Thread : public MessageQueue {
103 public:
104 explicit Thread(SocketServer* ss = NULL);
105 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
106 // guarantee Stop() is explicitly called before the subclass is destroyed).
107 // This is required to avoid a data race between the destructor modifying the
108 // vtable, and the Thread::PreRun calling the virtual method Run().
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000109 ~Thread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110
111 static Thread* Current();
112
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000113 // Used to catch performance regressions. Use this to disallow blocking calls
114 // (Invoke) for a given scope. If a synchronous call is made while this is in
115 // effect, an assert will be triggered.
116 // Note that this is a single threaded class.
117 class ScopedDisallowBlockingCalls {
118 public:
119 ScopedDisallowBlockingCalls();
120 ~ScopedDisallowBlockingCalls();
121 private:
122 Thread* const thread_;
123 const bool previous_state_;
124 };
125
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126 bool IsCurrent() const {
127 return Current() == this;
128 }
129
130 // Sleeps the calling thread for the specified number of milliseconds, during
131 // which time no processing is performed. Returns false if sleeping was
132 // interrupted by a signal (POSIX only).
133 static bool SleepMs(int millis);
134
135 // Sets the thread's name, for debugging. Must be called before Start().
136 // If |obj| is non-NULL, its value is appended to |name|.
137 const std::string& name() const { return name_; }
138 bool SetName(const std::string& name, const void* obj);
139
140 // Sets the thread's priority. Must be called before Start().
141 ThreadPriority priority() const { return priority_; }
142 bool SetPriority(ThreadPriority priority);
143
144 // Starts the execution of the thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 bool Start(Runnable* runnable = NULL);
146
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147 // Tells the thread to stop and waits until it is joined.
148 // Never call Stop on the current thread. Instead use the inherited Quit
149 // function which will exit the base MessageQueue without terminating the
150 // underlying OS thread.
151 virtual void Stop();
152
153 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
154 // work, override Run(). To receive and dispatch messages, call
155 // ProcessMessages occasionally.
156 virtual void Run();
157
158 virtual void Send(MessageHandler *phandler, uint32 id = 0,
159 MessageData *pdata = NULL);
160
161 // Convenience method to invoke a functor on another thread. Caller must
162 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
163 // Uses Send() internally, which blocks the current thread until execution
164 // is complete.
165 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000166 // NOTE: This function can only be called when synchronous calls are allowed.
167 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168 template <class ReturnT, class FunctorT>
169 ReturnT Invoke(const FunctorT& functor) {
170 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
171 Send(&handler);
172 return handler.result();
173 }
174
175 // From MessageQueue
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000176 void Clear(MessageHandler* phandler,
177 uint32 id = MQID_ANY,
178 MessageList* removed = NULL) override;
179 void ReceiveSends() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180
181 // ProcessMessages will process I/O and dispatch messages until:
182 // 1) cms milliseconds have elapsed (returns true)
183 // 2) Stop() is called (returns false)
184 bool ProcessMessages(int cms);
185
186 // Returns true if this is a thread that we created using the standard
187 // constructor, false if it was created by a call to
188 // ThreadManager::WrapCurrentThread(). The main thread of an application
189 // is generally not owned, since the OS representation of the thread
190 // obviously exists before we can get to it.
191 // You cannot call Start on non-owned threads.
192 bool IsOwned();
193
194#if defined(WEBRTC_WIN)
195 HANDLE GetHandle() const {
196 return thread_;
197 }
198 DWORD GetId() const {
199 return thread_id_;
200 }
201#elif defined(WEBRTC_POSIX)
202 pthread_t GetPThread() {
203 return thread_;
204 }
205#endif
206
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000207 // Expose private method running() for tests.
208 //
209 // DANGER: this is a terrible public API. Most callers that might want to
210 // call this likely do not have enough control/knowledge of the Thread in
211 // question to guarantee that the returned value remains true for the duration
212 // of whatever code is conditionally executing because of the return value!
213 bool RunningForTest() { return running(); }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000214
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000215 // Sets the per-thread allow-blocking-calls flag and returns the previous
jiayl@webrtc.org7dfb7fa2014-09-29 22:45:55 +0000216 // value. Must be called on this thread.
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000217 bool SetAllowBlockingCalls(bool allow);
218
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000219 // These functions are public to avoid injecting test hooks. Don't call them
220 // outside of tests.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000221 // This method should be called when thread is created using non standard
222 // method, like derived implementation of rtc::Thread and it can not be
223 // started by calling Start(). This will set started flag to true and
224 // owned to false. This must be called from the current thread.
225 bool WrapCurrent();
226 void UnwrapCurrent();
227
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000228 protected:
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000229 // Same as WrapCurrent except that it never fails as it does not try to
230 // acquire the synchronization access of the thread. The caller should never
231 // call Stop() or Join() on this thread.
232 void SafeWrapCurrent();
233
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234 // Blocks the calling thread until this thread has terminated.
235 void Join();
236
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000237 static void AssertBlockingIsAllowedOnCurrentThread();
238
239 friend class ScopedDisallowBlockingCalls;
240
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 private:
242 static void *PreRun(void *pv);
243
244 // ThreadManager calls this instead WrapCurrent() because
245 // ThreadManager::Instance() cannot be used while ThreadManager is
246 // being created.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000247 // The method tries to get synchronization rights of the thread on Windows if
248 // |need_synchronize_access| is true.
249 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
250 bool need_synchronize_access);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000252 // Return true if the thread was started and hasn't yet stopped.
253 bool running() { return running_.Wait(0); }
254
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000255 // Processes received "Send" requests. If |source| is not NULL, only requests
256 // from |source| are processed, otherwise, all requests are processed.
257 void ReceiveSendsFromThread(const Thread* source);
258
259 // If |source| is not NULL, pops the first "Send" message from |source| in
260 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
261 // The caller must lock |crit_| before calling.
262 // Returns true if there is such a message.
263 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
264
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 std::list<_SendMessage> sendlist_;
266 std::string name_;
267 ThreadPriority priority_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000268 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269
270#if defined(WEBRTC_POSIX)
271 pthread_t thread_;
272#endif
273
274#if defined(WEBRTC_WIN)
275 HANDLE thread_;
276 DWORD thread_id_;
277#endif
278
279 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000280 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281
282 friend class ThreadManager;
283
284 DISALLOW_COPY_AND_ASSIGN(Thread);
285};
286
287// AutoThread automatically installs itself at construction
288// uninstalls at destruction, if a Thread object is
289// _not already_ associated with the current OS thread.
290
291class AutoThread : public Thread {
292 public:
293 explicit AutoThread(SocketServer* ss = 0);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000294 ~AutoThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295
296 private:
297 DISALLOW_COPY_AND_ASSIGN(AutoThread);
298};
299
300// Win32 extension for threads that need to use COM
301#if defined(WEBRTC_WIN)
302class ComThread : public Thread {
303 public:
304 ComThread() {}
305 virtual ~ComThread() { Stop(); }
306
307 protected:
308 virtual void Run();
309
310 private:
311 DISALLOW_COPY_AND_ASSIGN(ComThread);
312};
313#endif
314
315// Provides an easy way to install/uninstall a socketserver on a thread.
316class SocketServerScope {
317 public:
318 explicit SocketServerScope(SocketServer* ss) {
319 old_ss_ = Thread::Current()->socketserver();
320 Thread::Current()->set_socketserver(ss);
321 }
322 ~SocketServerScope() {
323 Thread::Current()->set_socketserver(old_ss_);
324 }
325
326 private:
327 SocketServer* old_ss_;
328
329 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
330};
331
332} // namespace rtc
333
334#endif // WEBRTC_BASE_THREAD_H_