blob: 986335d983d39215985b6b84b3e6ddf115d579ec [file] [log] [blame]
henrike@webrtc.orgf7795df2014-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"
23#include "webrtc/base/messagequeue.h"
24
25#if defined(WEBRTC_WIN)
26#include "webrtc/base/win32.h"
27#endif
28
29namespace rtc {
30
31class Thread;
32
33class ThreadManager {
34 public:
35 ThreadManager();
36 ~ThreadManager();
37
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.
56 Thread *WrapCurrentThread();
57 void UnwrapCurrentThread();
58
59 private:
60#if defined(WEBRTC_POSIX)
61 pthread_key_t key_;
62#endif
63
64#if defined(WEBRTC_WIN)
65 DWORD key_;
66#endif
67
68 DISALLOW_COPY_AND_ASSIGN(ThreadManager);
69};
70
71struct _SendMessage {
72 _SendMessage() {}
73 Thread *thread;
74 Message msg;
75 bool *ready;
76};
77
78enum ThreadPriority {
79 PRIORITY_IDLE = -1,
80 PRIORITY_NORMAL = 0,
81 PRIORITY_ABOVE_NORMAL = 1,
82 PRIORITY_HIGH = 2,
83};
84
85class Runnable {
86 public:
87 virtual ~Runnable() {}
88 virtual void Run(Thread* thread) = 0;
89
90 protected:
91 Runnable() {}
92
93 private:
94 DISALLOW_COPY_AND_ASSIGN(Runnable);
95};
96
97// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
98
99class Thread : public MessageQueue {
100 public:
101 explicit Thread(SocketServer* ss = NULL);
102 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
103 // guarantee Stop() is explicitly called before the subclass is destroyed).
104 // This is required to avoid a data race between the destructor modifying the
105 // vtable, and the Thread::PreRun calling the virtual method Run().
106 virtual ~Thread();
107
108 static Thread* Current();
109
110 bool IsCurrent() const {
111 return Current() == this;
112 }
113
114 // Sleeps the calling thread for the specified number of milliseconds, during
115 // which time no processing is performed. Returns false if sleeping was
116 // interrupted by a signal (POSIX only).
117 static bool SleepMs(int millis);
118
119 // Sets the thread's name, for debugging. Must be called before Start().
120 // If |obj| is non-NULL, its value is appended to |name|.
121 const std::string& name() const { return name_; }
122 bool SetName(const std::string& name, const void* obj);
123
124 // Sets the thread's priority. Must be called before Start().
125 ThreadPriority priority() const { return priority_; }
126 bool SetPriority(ThreadPriority priority);
127
128 // Starts the execution of the thread.
129 bool started() const { return started_; }
130 bool Start(Runnable* runnable = NULL);
131
132 // Used for fire-and-forget threads. Deletes this thread object when the
133 // Run method returns.
134 void Release() {
135 delete_self_when_complete_ = true;
136 }
137
138 // Tells the thread to stop and waits until it is joined.
139 // Never call Stop on the current thread. Instead use the inherited Quit
140 // function which will exit the base MessageQueue without terminating the
141 // underlying OS thread.
142 virtual void Stop();
143
144 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
145 // work, override Run(). To receive and dispatch messages, call
146 // ProcessMessages occasionally.
147 virtual void Run();
148
149 virtual void Send(MessageHandler *phandler, uint32 id = 0,
150 MessageData *pdata = NULL);
151
152 // Convenience method to invoke a functor on another thread. Caller must
153 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
154 // Uses Send() internally, which blocks the current thread until execution
155 // is complete.
156 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
157 template <class ReturnT, class FunctorT>
158 ReturnT Invoke(const FunctorT& functor) {
159 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
160 Send(&handler);
161 return handler.result();
162 }
163
164 // From MessageQueue
165 virtual void Clear(MessageHandler *phandler, uint32 id = MQID_ANY,
166 MessageList* removed = NULL);
167 virtual void ReceiveSends();
168
169 // ProcessMessages will process I/O and dispatch messages until:
170 // 1) cms milliseconds have elapsed (returns true)
171 // 2) Stop() is called (returns false)
172 bool ProcessMessages(int cms);
173
174 // Returns true if this is a thread that we created using the standard
175 // constructor, false if it was created by a call to
176 // ThreadManager::WrapCurrentThread(). The main thread of an application
177 // is generally not owned, since the OS representation of the thread
178 // obviously exists before we can get to it.
179 // You cannot call Start on non-owned threads.
180 bool IsOwned();
181
182#if defined(WEBRTC_WIN)
183 HANDLE GetHandle() const {
184 return thread_;
185 }
186 DWORD GetId() const {
187 return thread_id_;
188 }
189#elif defined(WEBRTC_POSIX)
190 pthread_t GetPThread() {
191 return thread_;
192 }
193#endif
194
195 // This method should be called when thread is created using non standard
196 // method, like derived implementation of rtc::Thread and it can not be
197 // started by calling Start(). This will set started flag to true and
198 // owned to false. This must be called from the current thread.
199 // NOTE: These methods should be used by the derived classes only, added here
200 // only for testing.
201 bool WrapCurrent();
202 void UnwrapCurrent();
203
204 protected:
205 // Blocks the calling thread until this thread has terminated.
206 void Join();
207
208 private:
209 static void *PreRun(void *pv);
210
211 // ThreadManager calls this instead WrapCurrent() because
212 // ThreadManager::Instance() cannot be used while ThreadManager is
213 // being created.
214 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager);
215
216 std::list<_SendMessage> sendlist_;
217 std::string name_;
218 ThreadPriority priority_;
219 bool started_;
220
221#if defined(WEBRTC_POSIX)
222 pthread_t thread_;
223#endif
224
225#if defined(WEBRTC_WIN)
226 HANDLE thread_;
227 DWORD thread_id_;
228#endif
229
230 bool owned_;
231 bool delete_self_when_complete_;
232
233 friend class ThreadManager;
234
235 DISALLOW_COPY_AND_ASSIGN(Thread);
236};
237
238// AutoThread automatically installs itself at construction
239// uninstalls at destruction, if a Thread object is
240// _not already_ associated with the current OS thread.
241
242class AutoThread : public Thread {
243 public:
244 explicit AutoThread(SocketServer* ss = 0);
245 virtual ~AutoThread();
246
247 private:
248 DISALLOW_COPY_AND_ASSIGN(AutoThread);
249};
250
251// Win32 extension for threads that need to use COM
252#if defined(WEBRTC_WIN)
253class ComThread : public Thread {
254 public:
255 ComThread() {}
256 virtual ~ComThread() { Stop(); }
257
258 protected:
259 virtual void Run();
260
261 private:
262 DISALLOW_COPY_AND_ASSIGN(ComThread);
263};
264#endif
265
266// Provides an easy way to install/uninstall a socketserver on a thread.
267class SocketServerScope {
268 public:
269 explicit SocketServerScope(SocketServer* ss) {
270 old_ss_ = Thread::Current()->socketserver();
271 Thread::Current()->set_socketserver(ss);
272 }
273 ~SocketServerScope() {
274 Thread::Current()->set_socketserver(old_ss_);
275 }
276
277 private:
278 SocketServer* old_ss_;
279
280 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
281};
282
283} // namespace rtc
284
285#endif // WEBRTC_BASE_THREAD_H_