blob: 265054741475e4890e790efeaf43a538ce2185b4 [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().
109 virtual ~Thread();
110
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
176 virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
177 MessageList* removed = NULL);
178 virtual void ReceiveSends();
179
180 // ProcessMessages will process I/O and dispatch messages until:
181 // 1) cms milliseconds have elapsed (returns true)
182 // 2) Stop() is called (returns false)
183 bool ProcessMessages(int cms);
184
185 // Returns true if this is a thread that we created using the standard
186 // constructor, false if it was created by a call to
187 // ThreadManager::WrapCurrentThread(). The main thread of an application
188 // is generally not owned, since the OS representation of the thread
189 // obviously exists before we can get to it.
190 // You cannot call Start on non-owned threads.
191 bool IsOwned();
192
193#if defined(WEBRTC_WIN)
194 HANDLE GetHandle() const {
195 return thread_;
196 }
197 DWORD GetId() const {
198 return thread_id_;
199 }
200#elif defined(WEBRTC_POSIX)
201 pthread_t GetPThread() {
202 return thread_;
203 }
204#endif
205
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000206 // Expose private method running() for tests.
207 //
208 // DANGER: this is a terrible public API. Most callers that might want to
209 // call this likely do not have enough control/knowledge of the Thread in
210 // question to guarantee that the returned value remains true for the duration
211 // of whatever code is conditionally executing because of the return value!
212 bool RunningForTest() { return running(); }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000213
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000214 // Sets the per-thread allow-blocking-calls flag and returns the previous
jiayl@webrtc.org7dfb7fa2014-09-29 22:45:55 +0000215 // value. Must be called on this thread.
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000216 bool SetAllowBlockingCalls(bool allow);
217
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000218 // These functions are public to avoid injecting test hooks. Don't call them
219 // outside of tests.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000220 // This method should be called when thread is created using non standard
221 // method, like derived implementation of rtc::Thread and it can not be
222 // started by calling Start(). This will set started flag to true and
223 // owned to false. This must be called from the current thread.
224 bool WrapCurrent();
225 void UnwrapCurrent();
226
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000227 protected:
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000228 // Same as WrapCurrent except that it never fails as it does not try to
229 // acquire the synchronization access of the thread. The caller should never
230 // call Stop() or Join() on this thread.
231 void SafeWrapCurrent();
232
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000233 // Blocks the calling thread until this thread has terminated.
234 void Join();
235
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000236 static void AssertBlockingIsAllowedOnCurrentThread();
237
238 friend class ScopedDisallowBlockingCalls;
239
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 private:
241 static void *PreRun(void *pv);
242
243 // ThreadManager calls this instead WrapCurrent() because
244 // ThreadManager::Instance() cannot be used while ThreadManager is
245 // being created.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000246 // The method tries to get synchronization rights of the thread on Windows if
247 // |need_synchronize_access| is true.
248 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
249 bool need_synchronize_access);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000251 // Return true if the thread was started and hasn't yet stopped.
252 bool running() { return running_.Wait(0); }
253
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000254 // Processes received "Send" requests. If |source| is not NULL, only requests
255 // from |source| are processed, otherwise, all requests are processed.
256 void ReceiveSendsFromThread(const Thread* source);
257
258 // If |source| is not NULL, pops the first "Send" message from |source| in
259 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
260 // The caller must lock |crit_| before calling.
261 // Returns true if there is such a message.
262 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
263
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 std::list<_SendMessage> sendlist_;
265 std::string name_;
266 ThreadPriority priority_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000267 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268
269#if defined(WEBRTC_POSIX)
270 pthread_t thread_;
271#endif
272
273#if defined(WEBRTC_WIN)
274 HANDLE thread_;
275 DWORD thread_id_;
276#endif
277
278 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000279 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280
281 friend class ThreadManager;
282
283 DISALLOW_COPY_AND_ASSIGN(Thread);
284};
285
286// AutoThread automatically installs itself at construction
287// uninstalls at destruction, if a Thread object is
288// _not already_ associated with the current OS thread.
289
290class AutoThread : public Thread {
291 public:
292 explicit AutoThread(SocketServer* ss = 0);
293 virtual ~AutoThread();
294
295 private:
296 DISALLOW_COPY_AND_ASSIGN(AutoThread);
297};
298
299// Win32 extension for threads that need to use COM
300#if defined(WEBRTC_WIN)
301class ComThread : public Thread {
302 public:
303 ComThread() {}
304 virtual ~ComThread() { Stop(); }
305
306 protected:
307 virtual void Run();
308
309 private:
310 DISALLOW_COPY_AND_ASSIGN(ComThread);
311};
312#endif
313
314// Provides an easy way to install/uninstall a socketserver on a thread.
315class SocketServerScope {
316 public:
317 explicit SocketServerScope(SocketServer* ss) {
318 old_ss_ = Thread::Current()->socketserver();
319 Thread::Current()->set_socketserver(ss);
320 }
321 ~SocketServerScope() {
322 Thread::Current()->set_socketserver(old_ss_);
323 }
324
325 private:
326 SocketServer* old_ss_;
327
328 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
329};
330
331} // namespace rtc
332
333#endif // WEBRTC_BASE_THREAD_H_