blob: 9cbe8ec4dc54f1c5a2e9748b7e6a5782302ab3ff [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
henrikg3c089d72015-09-16 05:37:44 -070071 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072};
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:
henrikg3c089d72015-09-16 05:37:44 -070097 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000098};
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
Peter Boström0c4e06b2015-10-07 12:23:21 +0200158 virtual void Send(MessageHandler* phandler,
159 uint32_t id = 0,
160 MessageData* pdata = NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161
162 // Convenience method to invoke a functor on another thread. Caller must
163 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
164 // Uses Send() internally, which blocks the current thread until execution
165 // is complete.
166 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000167 // NOTE: This function can only be called when synchronous calls are allowed.
168 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 template <class ReturnT, class FunctorT>
170 ReturnT Invoke(const FunctorT& functor) {
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000171 InvokeBegin();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
173 Send(&handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000174 InvokeEnd();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 return handler.result();
176 }
177
178 // From MessageQueue
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000179 void Clear(MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200180 uint32_t id = MQID_ANY,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000181 MessageList* removed = NULL) override;
182 void ReceiveSends() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183
184 // ProcessMessages will process I/O and dispatch messages until:
185 // 1) cms milliseconds have elapsed (returns true)
186 // 2) Stop() is called (returns false)
187 bool ProcessMessages(int cms);
188
189 // Returns true if this is a thread that we created using the standard
190 // constructor, false if it was created by a call to
191 // ThreadManager::WrapCurrentThread(). The main thread of an application
192 // is generally not owned, since the OS representation of the thread
193 // obviously exists before we can get to it.
194 // You cannot call Start on non-owned threads.
195 bool IsOwned();
196
197#if defined(WEBRTC_WIN)
198 HANDLE GetHandle() const {
199 return thread_;
200 }
201 DWORD GetId() const {
202 return thread_id_;
203 }
204#elif defined(WEBRTC_POSIX)
205 pthread_t GetPThread() {
206 return thread_;
207 }
208#endif
209
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000210 // Expose private method running() for tests.
211 //
212 // DANGER: this is a terrible public API. Most callers that might want to
213 // call this likely do not have enough control/knowledge of the Thread in
214 // question to guarantee that the returned value remains true for the duration
215 // of whatever code is conditionally executing because of the return value!
216 bool RunningForTest() { return running(); }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000217
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000218 // Sets the per-thread allow-blocking-calls flag and returns the previous
jiayl@webrtc.org7dfb7fa2014-09-29 22:45:55 +0000219 // value. Must be called on this thread.
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000220 bool SetAllowBlockingCalls(bool allow);
221
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000222 // These functions are public to avoid injecting test hooks. Don't call them
223 // outside of tests.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000224 // This method should be called when thread is created using non standard
225 // method, like derived implementation of rtc::Thread and it can not be
226 // started by calling Start(). This will set started flag to true and
227 // owned to false. This must be called from the current thread.
228 bool WrapCurrent();
229 void UnwrapCurrent();
230
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000231 protected:
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000232 // Same as WrapCurrent except that it never fails as it does not try to
233 // acquire the synchronization access of the thread. The caller should never
234 // call Stop() or Join() on this thread.
235 void SafeWrapCurrent();
236
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237 // Blocks the calling thread until this thread has terminated.
238 void Join();
239
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000240 static void AssertBlockingIsAllowedOnCurrentThread();
241
242 friend class ScopedDisallowBlockingCalls;
243
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000244 private:
245 static void *PreRun(void *pv);
246
247 // ThreadManager calls this instead WrapCurrent() because
248 // ThreadManager::Instance() cannot be used while ThreadManager is
249 // being created.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000250 // The method tries to get synchronization rights of the thread on Windows if
251 // |need_synchronize_access| is true.
252 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
253 bool need_synchronize_access);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000255 // Return true if the thread was started and hasn't yet stopped.
256 bool running() { return running_.Wait(0); }
257
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000258 // Processes received "Send" requests. If |source| is not NULL, only requests
259 // from |source| are processed, otherwise, all requests are processed.
260 void ReceiveSendsFromThread(const Thread* source);
261
262 // If |source| is not NULL, pops the first "Send" message from |source| in
263 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
264 // The caller must lock |crit_| before calling.
265 // Returns true if there is such a message.
266 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
267
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000268 // Used for tracking performance of Invoke calls.
269 void InvokeBegin();
270 void InvokeEnd();
271
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272 std::list<_SendMessage> sendlist_;
273 std::string name_;
274 ThreadPriority priority_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000275 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276
277#if defined(WEBRTC_POSIX)
278 pthread_t thread_;
279#endif
280
281#if defined(WEBRTC_WIN)
282 HANDLE thread_;
283 DWORD thread_id_;
284#endif
285
286 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000287 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000288
289 friend class ThreadManager;
290
henrikg3c089d72015-09-16 05:37:44 -0700291 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292};
293
294// AutoThread automatically installs itself at construction
295// uninstalls at destruction, if a Thread object is
296// _not already_ associated with the current OS thread.
297
298class AutoThread : public Thread {
299 public:
300 explicit AutoThread(SocketServer* ss = 0);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000301 ~AutoThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302
303 private:
henrikg3c089d72015-09-16 05:37:44 -0700304 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305};
306
307// Win32 extension for threads that need to use COM
308#if defined(WEBRTC_WIN)
309class ComThread : public Thread {
310 public:
311 ComThread() {}
312 virtual ~ComThread() { Stop(); }
313
314 protected:
315 virtual void Run();
316
317 private:
henrikg3c089d72015-09-16 05:37:44 -0700318 RTC_DISALLOW_COPY_AND_ASSIGN(ComThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319};
320#endif
321
322// Provides an easy way to install/uninstall a socketserver on a thread.
323class SocketServerScope {
324 public:
325 explicit SocketServerScope(SocketServer* ss) {
326 old_ss_ = Thread::Current()->socketserver();
327 Thread::Current()->set_socketserver(ss);
328 }
329 ~SocketServerScope() {
330 Thread::Current()->set_socketserver(old_ss_);
331 }
332
333 private:
334 SocketServer* old_ss_;
335
henrikg3c089d72015-09-16 05:37:44 -0700336 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337};
338
339} // namespace rtc
340
341#endif // WEBRTC_BASE_THREAD_H_