blob: 6132aa0a79b866a902ab027a16cf35a14c2d3aaf [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:
36 ThreadManager();
37 ~ThreadManager();
38
39 static ThreadManager* Instance();
40
41 Thread* CurrentThread();
42 void SetCurrentThread(Thread* thread);
43
44 // Returns a thread object with its thread_ ivar set
45 // to whatever the OS uses to represent the thread.
46 // If there already *is* a Thread object corresponding to this thread,
47 // this method will return that. Otherwise it creates a new Thread
48 // object whose wrapped() method will return true, and whose
49 // handle will, on Win32, be opened with only synchronization privileges -
50 // if you need more privilegs, rather than changing this method, please
51 // write additional code to adjust the privileges, or call a different
52 // factory method of your own devising, because this one gets used in
53 // unexpected contexts (like inside browser plugins) and it would be a
54 // shame to break it. It is also conceivable on Win32 that we won't even
55 // be able to get synchronization privileges, in which case the result
56 // will have a NULL handle.
57 Thread *WrapCurrentThread();
58 void UnwrapCurrentThread();
59
60 private:
61#if defined(WEBRTC_POSIX)
62 pthread_key_t key_;
63#endif
64
65#if defined(WEBRTC_WIN)
66 DWORD key_;
67#endif
68
69 DISALLOW_COPY_AND_ASSIGN(ThreadManager);
70};
71
72struct _SendMessage {
73 _SendMessage() {}
74 Thread *thread;
75 Message msg;
76 bool *ready;
77};
78
79enum ThreadPriority {
80 PRIORITY_IDLE = -1,
81 PRIORITY_NORMAL = 0,
82 PRIORITY_ABOVE_NORMAL = 1,
83 PRIORITY_HIGH = 2,
84};
85
86class Runnable {
87 public:
88 virtual ~Runnable() {}
89 virtual void Run(Thread* thread) = 0;
90
91 protected:
92 Runnable() {}
93
94 private:
95 DISALLOW_COPY_AND_ASSIGN(Runnable);
96};
97
98// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
99
100class Thread : public MessageQueue {
101 public:
102 explicit Thread(SocketServer* ss = NULL);
103 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
104 // guarantee Stop() is explicitly called before the subclass is destroyed).
105 // This is required to avoid a data race between the destructor modifying the
106 // vtable, and the Thread::PreRun calling the virtual method Run().
107 virtual ~Thread();
108
109 static Thread* Current();
110
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000111 // Used to catch performance regressions. Use this to disallow blocking calls
112 // (Invoke) for a given scope. If a synchronous call is made while this is in
113 // effect, an assert will be triggered.
114 // Note that this is a single threaded class.
115 class ScopedDisallowBlockingCalls {
116 public:
117 ScopedDisallowBlockingCalls();
118 ~ScopedDisallowBlockingCalls();
119 private:
120 Thread* const thread_;
121 const bool previous_state_;
122 };
123
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124 bool IsCurrent() const {
125 return Current() == this;
126 }
127
128 // Sleeps the calling thread for the specified number of milliseconds, during
129 // which time no processing is performed. Returns false if sleeping was
130 // interrupted by a signal (POSIX only).
131 static bool SleepMs(int millis);
132
133 // Sets the thread's name, for debugging. Must be called before Start().
134 // If |obj| is non-NULL, its value is appended to |name|.
135 const std::string& name() const { return name_; }
136 bool SetName(const std::string& name, const void* obj);
137
138 // Sets the thread's priority. Must be called before Start().
139 ThreadPriority priority() const { return priority_; }
140 bool SetPriority(ThreadPriority priority);
141
142 // Starts the execution of the thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 bool Start(Runnable* runnable = NULL);
144
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 // Tells the thread to stop and waits until it is joined.
146 // Never call Stop on the current thread. Instead use the inherited Quit
147 // function which will exit the base MessageQueue without terminating the
148 // underlying OS thread.
149 virtual void Stop();
150
151 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
152 // work, override Run(). To receive and dispatch messages, call
153 // ProcessMessages occasionally.
154 virtual void Run();
155
156 virtual void Send(MessageHandler *phandler, uint32 id = 0,
157 MessageData *pdata = NULL);
158
159 // Convenience method to invoke a functor on another thread. Caller must
160 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
161 // Uses Send() internally, which blocks the current thread until execution
162 // is complete.
163 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000164 // NOTE: This function can only be called when synchronous calls are allowed.
165 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 template <class ReturnT, class FunctorT>
167 ReturnT Invoke(const FunctorT& functor) {
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000168 AssertBlockingIsAllowedOnCurrentThread();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
170 Send(&handler);
171 return handler.result();
172 }
173
174 // From MessageQueue
175 virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
176 MessageList* removed = NULL);
177 virtual void ReceiveSends();
178
179 // ProcessMessages will process I/O and dispatch messages until:
180 // 1) cms milliseconds have elapsed (returns true)
181 // 2) Stop() is called (returns false)
182 bool ProcessMessages(int cms);
183
184 // Returns true if this is a thread that we created using the standard
185 // constructor, false if it was created by a call to
186 // ThreadManager::WrapCurrentThread(). The main thread of an application
187 // is generally not owned, since the OS representation of the thread
188 // obviously exists before we can get to it.
189 // You cannot call Start on non-owned threads.
190 bool IsOwned();
191
192#if defined(WEBRTC_WIN)
193 HANDLE GetHandle() const {
194 return thread_;
195 }
196 DWORD GetId() const {
197 return thread_id_;
198 }
199#elif defined(WEBRTC_POSIX)
200 pthread_t GetPThread() {
201 return thread_;
202 }
203#endif
204
205 // This method should be called when thread is created using non standard
206 // method, like derived implementation of rtc::Thread and it can not be
207 // started by calling Start(). This will set started flag to true and
208 // owned to false. This must be called from the current thread.
209 // NOTE: These methods should be used by the derived classes only, added here
210 // only for testing.
211 bool WrapCurrent();
212 void UnwrapCurrent();
213
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000214 // Expose private method running() for tests.
215 //
216 // DANGER: this is a terrible public API. Most callers that might want to
217 // call this likely do not have enough control/knowledge of the Thread in
218 // question to guarantee that the returned value remains true for the duration
219 // of whatever code is conditionally executing because of the return value!
220 bool RunningForTest() { return running(); }
221 // This is a legacy call-site that probably doesn't need to exist in the first
222 // place.
223 // TODO(fischman): delete once the ASSERT added in channelmanager.cc sticks
224 // for a month (ETA 2014/06/22).
225 bool RunningForChannelManager() { return running(); }
226
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000227 protected:
228 // Blocks the calling thread until this thread has terminated.
229 void Join();
230
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000231 // Sets the per-thread allow-blocking-calls flag and returns the previous
232 // value.
233 bool SetAllowBlockingCalls(bool allow);
234
235 static void AssertBlockingIsAllowedOnCurrentThread();
236
237 friend class ScopedDisallowBlockingCalls;
238
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 private:
240 static void *PreRun(void *pv);
241
242 // ThreadManager calls this instead WrapCurrent() because
243 // ThreadManager::Instance() cannot be used while ThreadManager is
244 // being created.
245 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager);
246
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000247 // Return true if the thread was started and hasn't yet stopped.
248 bool running() { return running_.Wait(0); }
249
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 std::list<_SendMessage> sendlist_;
251 std::string name_;
252 ThreadPriority priority_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000253 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
255#if defined(WEBRTC_POSIX)
256 pthread_t thread_;
257#endif
258
259#if defined(WEBRTC_WIN)
260 HANDLE thread_;
261 DWORD thread_id_;
262#endif
263
264 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000265 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266
267 friend class ThreadManager;
268
269 DISALLOW_COPY_AND_ASSIGN(Thread);
270};
271
272// AutoThread automatically installs itself at construction
273// uninstalls at destruction, if a Thread object is
274// _not already_ associated with the current OS thread.
275
276class AutoThread : public Thread {
277 public:
278 explicit AutoThread(SocketServer* ss = 0);
279 virtual ~AutoThread();
280
281 private:
282 DISALLOW_COPY_AND_ASSIGN(AutoThread);
283};
284
285// Win32 extension for threads that need to use COM
286#if defined(WEBRTC_WIN)
287class ComThread : public Thread {
288 public:
289 ComThread() {}
290 virtual ~ComThread() { Stop(); }
291
292 protected:
293 virtual void Run();
294
295 private:
296 DISALLOW_COPY_AND_ASSIGN(ComThread);
297};
298#endif
299
300// Provides an easy way to install/uninstall a socketserver on a thread.
301class SocketServerScope {
302 public:
303 explicit SocketServerScope(SocketServer* ss) {
304 old_ss_ = Thread::Current()->socketserver();
305 Thread::Current()->set_socketserver(ss);
306 }
307 ~SocketServerScope() {
308 Thread::Current()->set_socketserver(old_ss_);
309 }
310
311 private:
312 SocketServer* old_ss_;
313
314 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
315};
316
317} // namespace rtc
318
319#endif // WEBRTC_BASE_THREAD_H_