blob: 6e5da61005b6ba3357bc0a85e1df98c594c7c0f1 [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"
nisse7866cfe2017-04-26 01:45:31 -070026#include "webrtc/base/platform_thread_types.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027
28#if defined(WEBRTC_WIN)
29#include "webrtc/base/win32.h"
30#endif
31
32namespace rtc {
33
34class Thread;
35
36class ThreadManager {
37 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +000038 static const int kForever = -1;
39
nisse7866cfe2017-04-26 01:45:31 -070040 // Singleton, constructor and destructor are private.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 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
deadbeef37f5ecf2017-02-27 14:06:41 -080058 // will have a null handle.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 Thread *WrapCurrentThread();
60 void UnwrapCurrentThread();
61
nisse7866cfe2017-04-26 01:45:31 -070062 bool IsMainThread();
63
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064 private:
nisse7866cfe2017-04-26 01:45:31 -070065 ThreadManager();
66 ~ThreadManager();
67
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068#if defined(WEBRTC_POSIX)
69 pthread_key_t key_;
70#endif
71
72#if defined(WEBRTC_WIN)
73 DWORD key_;
74#endif
75
nisse7866cfe2017-04-26 01:45:31 -070076 // The thread to potentially autowrap.
77 PlatformThreadRef main_thread_ref_;
78
henrikg3c089d72015-09-16 05:37:44 -070079 RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080};
81
82struct _SendMessage {
83 _SendMessage() {}
84 Thread *thread;
85 Message msg;
86 bool *ready;
87};
88
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000089class Runnable {
90 public:
91 virtual ~Runnable() {}
92 virtual void Run(Thread* thread) = 0;
93
94 protected:
95 Runnable() {}
96
97 private:
henrikg3c089d72015-09-16 05:37:44 -070098 RTC_DISALLOW_COPY_AND_ASSIGN(Runnable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099};
100
101// WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
102
danilchap8e572f02016-05-19 06:49:03 -0700103class LOCKABLE Thread : public MessageQueue {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104 public:
jbauch25d1f282016-02-05 00:25:02 -0800105 // Create a new Thread and optionally assign it to the passed SocketServer.
danilchapbebf54c2016-04-28 01:32:48 -0700106 Thread();
107 explicit Thread(SocketServer* ss);
108 explicit Thread(std::unique_ptr<SocketServer> ss);
jbauch25d1f282016-02-05 00:25:02 -0800109
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110 // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
111 // guarantee Stop() is explicitly called before the subclass is destroyed).
112 // This is required to avoid a data race between the destructor modifying the
113 // vtable, and the Thread::PreRun calling the virtual method Run().
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000114 ~Thread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115
danilchapbebf54c2016-04-28 01:32:48 -0700116 static std::unique_ptr<Thread> CreateWithSocketServer();
117 static std::unique_ptr<Thread> Create();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 static Thread* Current();
119
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000120 // Used to catch performance regressions. Use this to disallow blocking calls
121 // (Invoke) for a given scope. If a synchronous call is made while this is in
122 // effect, an assert will be triggered.
123 // Note that this is a single threaded class.
124 class ScopedDisallowBlockingCalls {
125 public:
126 ScopedDisallowBlockingCalls();
127 ~ScopedDisallowBlockingCalls();
128 private:
129 Thread* const thread_;
130 const bool previous_state_;
131 };
132
nisse7866cfe2017-04-26 01:45:31 -0700133 bool IsCurrent() const;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134
135 // Sleeps the calling thread for the specified number of milliseconds, during
136 // which time no processing is performed. Returns false if sleeping was
137 // interrupted by a signal (POSIX only).
138 static bool SleepMs(int millis);
139
140 // Sets the thread's name, for debugging. Must be called before Start().
deadbeef37f5ecf2017-02-27 14:06:41 -0800141 // If |obj| is non-null, its value is appended to |name|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 const std::string& name() const { return name_; }
143 bool SetName(const std::string& name, const void* obj);
144
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 // Starts the execution of the thread.
deadbeef37f5ecf2017-02-27 14:06:41 -0800146 bool Start(Runnable* runnable = nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 // Tells the thread to stop and waits until it is joined.
149 // Never call Stop on the current thread. Instead use the inherited Quit
150 // function which will exit the base MessageQueue without terminating the
151 // underlying OS thread.
152 virtual void Stop();
153
154 // By default, Thread::Run() calls ProcessMessages(kForever). To do other
155 // work, override Run(). To receive and dispatch messages, call
156 // ProcessMessages occasionally.
157 virtual void Run();
158
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700159 virtual void Send(const Location& posted_from,
160 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200161 uint32_t id = 0,
deadbeef37f5ecf2017-02-27 14:06:41 -0800162 MessageData* pdata = nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163
164 // Convenience method to invoke a functor on another thread. Caller must
165 // provide the |ReturnT| template argument, which cannot (easily) be deduced.
166 // Uses Send() internally, which blocks the current thread until execution
167 // is complete.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700168 // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
169 // &MyFunctionReturningBool);
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000170 // NOTE: This function can only be called when synchronous calls are allowed.
171 // See ScopedDisallowBlockingCalls for details.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 template <class ReturnT, class FunctorT>
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700173 ReturnT Invoke(const Location& posted_from, const FunctorT& functor) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000174 FunctorMessageHandler<ReturnT, FunctorT> handler(functor);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700175 InvokeInternal(posted_from, &handler);
deadbeef81baed32017-02-10 18:11:11 -0800176 return handler.MoveResult();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 }
178
179 // From MessageQueue
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000180 void Clear(MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200181 uint32_t id = MQID_ANY,
deadbeef37f5ecf2017-02-27 14:06:41 -0800182 MessageList* removed = nullptr) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000183 void ReceiveSends() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184
185 // ProcessMessages will process I/O and dispatch messages until:
186 // 1) cms milliseconds have elapsed (returns true)
187 // 2) Stop() is called (returns false)
188 bool ProcessMessages(int cms);
189
190 // Returns true if this is a thread that we created using the standard
191 // constructor, false if it was created by a call to
192 // ThreadManager::WrapCurrentThread(). The main thread of an application
193 // is generally not owned, since the OS representation of the thread
194 // obviously exists before we can get to it.
195 // You cannot call Start on non-owned threads.
196 bool IsOwned();
197
198#if defined(WEBRTC_WIN)
199 HANDLE GetHandle() const {
200 return thread_;
201 }
202 DWORD GetId() const {
203 return thread_id_;
204 }
205#elif defined(WEBRTC_POSIX)
206 pthread_t GetPThread() {
207 return thread_;
208 }
209#endif
210
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000211 // Expose private method running() for tests.
212 //
213 // DANGER: this is a terrible public API. Most callers that might want to
214 // call this likely do not have enough control/knowledge of the Thread in
215 // question to guarantee that the returned value remains true for the duration
216 // of whatever code is conditionally executing because of the return value!
217 bool RunningForTest() { return running(); }
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000218
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000219 // Sets the per-thread allow-blocking-calls flag and returns the previous
jiayl@webrtc.org7dfb7fa2014-09-29 22:45:55 +0000220 // value. Must be called on this thread.
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000221 bool SetAllowBlockingCalls(bool allow);
222
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000223 // These functions are public to avoid injecting test hooks. Don't call them
224 // outside of tests.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000225 // This method should be called when thread is created using non standard
226 // method, like derived implementation of rtc::Thread and it can not be
227 // started by calling Start(). This will set started flag to true and
228 // owned to false. This must be called from the current thread.
229 bool WrapCurrent();
230 void UnwrapCurrent();
231
henrike@webrtc.orge30dab72014-10-09 15:41:40 +0000232 protected:
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000233 // Same as WrapCurrent except that it never fails as it does not try to
234 // acquire the synchronization access of the thread. The caller should never
235 // call Stop() or Join() on this thread.
236 void SafeWrapCurrent();
237
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238 // Blocks the calling thread until this thread has terminated.
239 void Join();
240
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000241 static void AssertBlockingIsAllowedOnCurrentThread();
242
243 friend class ScopedDisallowBlockingCalls;
244
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245 private:
kthelgason61abe152017-03-29 02:32:36 -0700246 struct ThreadInit {
247 Thread* thread;
248 Runnable* runnable;
249 };
250
deadbeefdc20e262017-01-31 15:10:44 -0800251#if defined(WEBRTC_WIN)
252 static DWORD WINAPI PreRun(LPVOID context);
253#else
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 static void *PreRun(void *pv);
deadbeefdc20e262017-01-31 15:10:44 -0800255#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
257 // ThreadManager calls this instead WrapCurrent() because
258 // ThreadManager::Instance() cannot be used while ThreadManager is
259 // being created.
jiayl@webrtc.orgba737cb2014-09-18 16:45:21 +0000260 // The method tries to get synchronization rights of the thread on Windows if
261 // |need_synchronize_access| is true.
262 bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
263 bool need_synchronize_access);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000265 // Return true if the thread was started and hasn't yet stopped.
266 bool running() { return running_.Wait(0); }
267
deadbeef37f5ecf2017-02-27 14:06:41 -0800268 // Processes received "Send" requests. If |source| is not null, only requests
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000269 // from |source| are processed, otherwise, all requests are processed.
270 void ReceiveSendsFromThread(const Thread* source);
271
deadbeef37f5ecf2017-02-27 14:06:41 -0800272 // If |source| is not null, pops the first "Send" message from |source| in
jiayl@webrtc.org3987b6d2014-09-24 17:14:05 +0000273 // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
274 // The caller must lock |crit_| before calling.
275 // Returns true if there is such a message.
276 bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
277
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700278 void InvokeInternal(const Location& posted_from, MessageHandler* handler);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +0000279
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280 std::list<_SendMessage> sendlist_;
281 std::string name_;
fischman@webrtc.orge5063b12014-05-23 17:28:50 +0000282 Event running_; // Signalled means running.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283
284#if defined(WEBRTC_POSIX)
285 pthread_t thread_;
286#endif
287
288#if defined(WEBRTC_WIN)
289 HANDLE thread_;
290 DWORD thread_id_;
291#endif
292
293 bool owned_;
henrike@webrtc.org92a9bac2014-07-14 22:03:57 +0000294 bool blocking_calls_allowed_; // By default set to |true|.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295
296 friend class ThreadManager;
297
henrikg3c089d72015-09-16 05:37:44 -0700298 RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299};
300
301// AutoThread automatically installs itself at construction
302// uninstalls at destruction, if a Thread object is
303// _not already_ associated with the current OS thread.
304
305class AutoThread : public Thread {
306 public:
danilchapbebf54c2016-04-28 01:32:48 -0700307 AutoThread();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000308 ~AutoThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309
310 private:
henrikg3c089d72015-09-16 05:37:44 -0700311 RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312};
313
nisse7eaa4ea2017-05-08 05:25:41 -0700314// AutoSocketServerThread automatically installs itself at
315// construction and uninstalls at destruction. If a Thread object is
316// already associated with the current OS thread, it is temporarily
317// disassociated and restored by the destructor.
318
319class AutoSocketServerThread : public Thread {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320 public:
nisse7eaa4ea2017-05-08 05:25:41 -0700321 explicit AutoSocketServerThread(SocketServer* ss);
322 ~AutoSocketServerThread() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323
324 private:
nisse7eaa4ea2017-05-08 05:25:41 -0700325 rtc::Thread* old_thread_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326
nisse7eaa4ea2017-05-08 05:25:41 -0700327 RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328};
329
330} // namespace rtc
331
332#endif // WEBRTC_BASE_THREAD_H_