blob: 58fa3f0d463b5ee0c6e1f83ae5fc4aaadcc875e6 [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>
kwibergbfefb032016-05-01 14:53:46 -070016#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017#include <string>
18#include <vector>
19
20#if defined(WEBRTC_POSIX)
21#include <pthread.h>
22#endif
23#include "webrtc/base/constructormagic.h"
fischman@webrtc.orge5063b12014-05-23 17:28:50 +000024#include "webrtc/base/event.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025#include "webrtc/base/messagequeue.h"
26
27#if defined(WEBRTC_WIN)
28#include "webrtc/base/win32.h"
29#endif
30
31namespace rtc {
32
33class Thread;
34
35class ThreadManager {
36 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +000037 static const int kForever = -1;
38
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039 ThreadManager();
40 ~ThreadManager();
41
42 static ThreadManager* Instance();
43
44 Thread* CurrentThread();
45 void SetCurrentThread(Thread* thread);
46
47 // Returns a thread object with its thread_ ivar set
48 // to whatever the OS uses to represent the thread.
49 // If there already *is* a Thread object corresponding to this thread,
50 // this method will return that. Otherwise it creates a new Thread
51 // object whose wrapped() method will return true, and whose
52 // handle will, on Win32, be opened with only synchronization privileges -
53 // if you need more privilegs, rather than changing this method, please
54 // write additional code to adjust the privileges, or call a different
55 // factory method of your own devising, because this one gets used in
56 // unexpected contexts (like inside browser plugins) and it would be a
57 // shame to break it. It is also conceivable on Win32 that we won't even
58 // be able to get synchronization privileges, in which case the result
59 // will have a NULL handle.
60 Thread *WrapCurrentThread();
61 void UnwrapCurrentThread();
62
63 private:
64#if defined(WEBRTC_POSIX)
65 pthread_key_t key_;
66#endif
67
68#if defined(WEBRTC_WIN)
69 DWORD key_;
70#endif
71
henrikg3c089d72015-09-16 05:37:44 -070072 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000073};
74
75struct _SendMessage {
76 _SendMessage() {}
77 Thread *thread;
78 Message msg;
79 bool *ready;
80};
81
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000082class Runnable {
83 public:
84 virtual ~Runnable() {}
85 virtual void Run(Thread* thread) = 0;
86
87 protected:
88 Runnable() {}
89
90 private:
henrikg3c089d72015-09-16 05:37:44 -070091 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092};
93
94// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
95
danilchap8e572f02016-05-19 06:49:03 -070096class LOCKABLE Thread : public MessageQueue {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000097 public:
jbauch25d1f282016-02-05 00:25:02 -080098 // Create a new Thread and optionally assign it to the passed SocketServer.
danilchapbebf54c2016-04-28 01:32:48 -070099 Thread();
100 explicit Thread(SocketServer* ss);
101 explicit Thread(std::unique_ptr<SocketServer> ss);
jbauch25d1f282016-02-05 00:25:02 -0800102
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 // 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().
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000107 ~Thread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108
danilchapbebf54c2016-04-28 01:32:48 -0700109 static std::unique_ptr<Thread> CreateWithSocketServer();
110 static std::unique_ptr<Thread> Create();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 // Starts the execution of the thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 bool Start(Runnable* runnable = NULL);
142
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 // Tells the thread to stop and waits until it is joined.
144 // Never call Stop on the current thread. Instead use the inherited Quit
145 // function which will exit the base MessageQueue without terminating the
146 // underlying OS thread.
147 virtual void Stop();
148
149 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
150 // work, override Run(). To receive and dispatch messages, call
151 // ProcessMessages occasionally.
152 virtual void Run();
153
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700154 virtual void Send(const Location& posted_from,
155 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200156 uint32_t id = 0,
157 MessageData* pdata = NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000158
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.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700163 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
164 // &MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000165 // NOTE: This function can only be called when synchronous calls are allowed.
166 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 template <class ReturnT, class FunctorT>
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700168 ReturnT Invoke(const Location& posted_from, const FunctorT& functor) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700170 InvokeInternal(posted_from, &handler);
deadbeef81baed32017-02-10 18:11:11 -0800171 return handler.MoveResult();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 }
173
174 // From MessageQueue
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000175 void Clear(MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200176 uint32_t id = MQID_ANY,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000177 MessageList* removed = NULL) override;
178 void ReceiveSends() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179
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:
deadbeefdc20e262017-01-31 15:10:44 -0800241#if defined(WEBRTC_WIN)
242 static DWORD WINAPI PreRun(LPVOID context);
243#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000244 static void *PreRun(void *pv);
deadbeefdc20e262017-01-31 15:10:44 -0800245#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246
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
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700268 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000269
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 std::list<_SendMessage> sendlist_;
271 std::string name_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000272 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273
274#if defined(WEBRTC_POSIX)
275 pthread_t thread_;
276#endif
277
278#if defined(WEBRTC_WIN)
279 HANDLE thread_;
280 DWORD thread_id_;
281#endif
282
283 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000284 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285
286 friend class ThreadManager;
287
henrikg3c089d72015-09-16 05:37:44 -0700288 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289};
290
291// AutoThread automatically installs itself at construction
292// uninstalls at destruction, if a Thread object is
293// _not already_ associated with the current OS thread.
294
295class AutoThread : public Thread {
296 public:
danilchapbebf54c2016-04-28 01:32:48 -0700297 AutoThread();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000298 ~AutoThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299
300 private:
henrikg3c089d72015-09-16 05:37:44 -0700301 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302};
303
304// Win32 extension for threads that need to use COM
305#if defined(WEBRTC_WIN)
306class ComThread : public Thread {
307 public:
308 ComThread() {}
aleloi8dd4ec32017-02-20 04:17:53 -0800309 ~ComThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310
311 protected:
jbauch25d1f282016-02-05 00:25:02 -0800312 void Run() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313
314 private:
henrikg3c089d72015-09-16 05:37:44 -0700315 RTC_DISALLOW_COPY_AND_ASSIGN(ComThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316};
317#endif
318
319// Provides an easy way to install/uninstall a socketserver on a thread.
320class SocketServerScope {
321 public:
322 explicit SocketServerScope(SocketServer* ss) {
323 old_ss_ = Thread::Current()->socketserver();
324 Thread::Current()->set_socketserver(ss);
325 }
326 ~SocketServerScope() {
327 Thread::Current()->set_socketserver(old_ss_);
328 }
329
330 private:
331 SocketServer* old_ss_;
332
henrikg3c089d72015-09-16 05:37:44 -0700333 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(SocketServerScope);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334};
335
336} // namespace rtc
337
338#endif // WEBRTC_BASE_THREAD_H_