blob: 7623424104a0b87dcd9d6a9223eb76f07340dd08 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081class Runnable {
82 public:
83 virtual ~Runnable() {}
84 virtual void Run(Thread* thread) = 0;
85
86 protected:
87 Runnable() {}
88
89 private:
henrikg3c089d72015-09-16 05:37:44 -070090 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091};
92
93// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
94
95class Thread : public MessageQueue {
96 public:
jbauch25d1f282016-02-05 00:25:02 -080097 // Create a new Thread and optionally assign it to the passed SocketServer.
danilchapbebf54c2016-04-28 01:32:48 -070098 Thread();
99 explicit Thread(SocketServer* ss);
100 explicit Thread(std::unique_ptr<SocketServer> ss);
jbauch25d1f282016-02-05 00:25:02 -0800101
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102 // 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().
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000106 ~Thread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107
danilchapbebf54c2016-04-28 01:32:48 -0700108 static std::unique_ptr<Thread> CreateWithSocketServer();
109 static std::unique_ptr<Thread> Create();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110 static Thread* Current();
111
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000112 // Used to catch performance regressions. Use this to disallow blocking calls
113 // (Invoke) for a given scope. If a synchronous call is made while this is in
114 // effect, an assert will be triggered.
115 // Note that this is a single threaded class.
116 class ScopedDisallowBlockingCalls {
117 public:
118 ScopedDisallowBlockingCalls();
119 ~ScopedDisallowBlockingCalls();
120 private:
121 Thread* const thread_;
122 const bool previous_state_;
123 };
124
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125 bool IsCurrent() const {
126 return Current() == this;
127 }
128
129 // Sleeps the calling thread for the specified number of milliseconds, during
130 // which time no processing is performed. Returns false if sleeping was
131 // interrupted by a signal (POSIX only).
132 static bool SleepMs(int millis);
133
134 // Sets the thread's name, for debugging. Must be called before Start().
135 // If |obj| is non-NULL, its value is appended to |name|.
136 const std::string& name() const { return name_; }
137 bool SetName(const std::string& name, const void* obj);
138
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 // Starts the execution of the thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 bool Start(Runnable* runnable = NULL);
141
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 // Tells the thread to stop and waits until it is joined.
143 // Never call Stop on the current thread. Instead use the inherited Quit
144 // function which will exit the base MessageQueue without terminating the
145 // underlying OS thread.
146 virtual void Stop();
147
148 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
149 // work, override Run(). To receive and dispatch messages, call
150 // ProcessMessages occasionally.
151 virtual void Run();
152
Peter Boström0c4e06b2015-10-07 12:23:21 +0200153 virtual void Send(MessageHandler* phandler,
154 uint32_t id = 0,
155 MessageData* pdata = NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156
157 // Convenience method to invoke a functor on another thread. Caller must
158 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
159 // Uses Send() internally, which blocks the current thread until execution
160 // is complete.
161 // Ex: bool result = thread.Invoke<bool>(&MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000162 // NOTE: This function can only be called when synchronous calls are allowed.
163 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164 template <class ReturnT, class FunctorT>
165 ReturnT Invoke(const FunctorT& functor) {
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000166 InvokeBegin();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
168 Send(&handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000169 InvokeEnd();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 return handler.result();
171 }
172
173 // From MessageQueue
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000174 void Clear(MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200175 uint32_t id = MQID_ANY,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000176 MessageList* removed = NULL) override;
177 void ReceiveSends() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178
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
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000205 // Expose private method running() for tests.
206 //
207 // DANGER: this is a terrible public API. Most callers that might want to
208 // call this likely do not have enough control/knowledge of the Thread in
209 // question to guarantee that the returned value remains true for the duration
210 // of whatever code is conditionally executing because of the return value!
211 bool RunningForTest() { return running(); }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000212
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000213 // Sets the per-thread allow-blocking-calls flag and returns the previous
jiayl@webrtc.org7dfb7fa2014-09-29 22:45:55 +0000214 // value. Must be called on this thread.
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000215 bool SetAllowBlockingCalls(bool allow);
216
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000217 // These functions are public to avoid injecting test hooks. Don't call them
218 // outside of tests.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000219 // This method should be called when thread is created using non standard
220 // method, like derived implementation of rtc::Thread and it can not be
221 // started by calling Start(). This will set started flag to true and
222 // owned to false. This must be called from the current thread.
223 bool WrapCurrent();
224 void UnwrapCurrent();
225
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000226 protected:
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000227 // Same as WrapCurrent except that it never fails as it does not try to
228 // acquire the synchronization access of the thread. The caller should never
229 // call Stop() or Join() on this thread.
230 void SafeWrapCurrent();
231
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232 // Blocks the calling thread until this thread has terminated.
233 void Join();
234
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000235 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.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000245 // The method tries to get synchronization rights of the thread on Windows if
246 // |need_synchronize_access| is true.
247 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
248 bool need_synchronize_access);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000250 // Return true if the thread was started and hasn't yet stopped.
251 bool running() { return running_.Wait(0); }
252
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000253 // Processes received "Send" requests. If |source| is not NULL, only requests
254 // from |source| are processed, otherwise, all requests are processed.
255 void ReceiveSendsFromThread(const Thread* source);
256
257 // If |source| is not NULL, pops the first "Send" message from |source| in
258 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
259 // The caller must lock |crit_| before calling.
260 // Returns true if there is such a message.
261 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
262
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000263 // Used for tracking performance of Invoke calls.
264 void InvokeBegin();
265 void InvokeEnd();
266
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 std::list<_SendMessage> sendlist_;
268 std::string name_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000269 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270
271#if defined(WEBRTC_POSIX)
272 pthread_t thread_;
273#endif
274
275#if defined(WEBRTC_WIN)
276 HANDLE thread_;
277 DWORD thread_id_;
278#endif
279
280 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000281 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
283 friend class ThreadManager;
284
henrikg3c089d72015-09-16 05:37:44 -0700285 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286};
287
288// AutoThread automatically installs itself at construction
289// uninstalls at destruction, if a Thread object is
290// _not already_ associated with the current OS thread.
291
292class AutoThread : public Thread {
293 public:
danilchapbebf54c2016-04-28 01:32:48 -0700294 AutoThread();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000295 ~AutoThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296
297 private:
henrikg3c089d72015-09-16 05:37:44 -0700298 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299};
300
301// Win32 extension for threads that need to use COM
302#if defined(WEBRTC_WIN)
303class ComThread : public Thread {
304 public:
305 ComThread() {}
jbauch25d1f282016-02-05 00:25:02 -0800306 ~ComThread() override { Stop(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307
308 protected:
jbauch25d1f282016-02-05 00:25:02 -0800309 void Run() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310
311 private:
henrikg3c089d72015-09-16 05:37:44 -0700312 RTC_DISALLOW_COPY_AND_ASSIGN(ComThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313};
314#endif
315
316// Provides an easy way to install/uninstall a socketserver on a thread.
317class SocketServerScope {
318 public:
319 explicit SocketServerScope(SocketServer* ss) {
320 old_ss_ = Thread::Current()->socketserver();
321 Thread::Current()->set_socketserver(ss);
322 }
323 ~SocketServerScope() {
324 Thread::Current()->set_socketserver(old_ss_);
325 }
326
327 private:
328 SocketServer* old_ss_;
329
henrikg3c089d72015-09-16 05:37:44 -0700330 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331};
332
333} // namespace rtc
334
335#endif // WEBRTC_BASE_THREAD_H_