You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

420 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #ifndef RTC_BASE_THREAD_H_
  11. #define RTC_BASE_THREAD_H_
  12. #include <stdint.h>
  13. #include <list>
  14. #include <memory>
  15. #include <string>
  16. #include <type_traits>
  17. #if defined(WEBRTC_POSIX)
  18. #include <pthread.h>
  19. #endif
  20. #include "rtc_base/constructor_magic.h"
  21. #include "rtc_base/location.h"
  22. #include "rtc_base/message_handler.h"
  23. #include "rtc_base/message_queue.h"
  24. #include "rtc_base/platform_thread_types.h"
  25. #include "rtc_base/socket_server.h"
  26. #include "rtc_base/system/rtc_export.h"
  27. #include "rtc_base/thread_annotations.h"
  28. #if defined(WEBRTC_WIN)
  29. #include "rtc_base/win32.h"
  30. #endif
  31. namespace rtc {
  32. class Thread;
  33. namespace rtc_thread_internal {
  34. class MessageLikeTask : public MessageData {
  35. public:
  36. virtual void Run() = 0;
  37. };
  38. template <class FunctorT>
  39. class MessageWithFunctor final : public MessageLikeTask {
  40. public:
  41. explicit MessageWithFunctor(FunctorT&& functor)
  42. : functor_(std::forward<FunctorT>(functor)) {}
  43. void Run() override { functor_(); }
  44. private:
  45. ~MessageWithFunctor() override {}
  46. typename std::remove_reference<FunctorT>::type functor_;
  47. RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
  48. };
  49. class MessageHandlerWithTask final : public MessageHandler {
  50. public:
  51. MessageHandlerWithTask() = default;
  52. void OnMessage(Message* msg) override {
  53. static_cast<MessageLikeTask*>(msg->pdata)->Run();
  54. delete msg->pdata;
  55. }
  56. private:
  57. ~MessageHandlerWithTask() override {}
  58. RTC_DISALLOW_COPY_AND_ASSIGN(MessageHandlerWithTask);
  59. };
  60. } // namespace rtc_thread_internal
  61. class RTC_EXPORT ThreadManager {
  62. public:
  63. static const int kForever = -1;
  64. // Singleton, constructor and destructor are private.
  65. static ThreadManager* Instance();
  66. Thread* CurrentThread();
  67. void SetCurrentThread(Thread* thread);
  68. // Returns a thread object with its thread_ ivar set
  69. // to whatever the OS uses to represent the thread.
  70. // If there already *is* a Thread object corresponding to this thread,
  71. // this method will return that. Otherwise it creates a new Thread
  72. // object whose wrapped() method will return true, and whose
  73. // handle will, on Win32, be opened with only synchronization privileges -
  74. // if you need more privilegs, rather than changing this method, please
  75. // write additional code to adjust the privileges, or call a different
  76. // factory method of your own devising, because this one gets used in
  77. // unexpected contexts (like inside browser plugins) and it would be a
  78. // shame to break it. It is also conceivable on Win32 that we won't even
  79. // be able to get synchronization privileges, in which case the result
  80. // will have a null handle.
  81. Thread* WrapCurrentThread();
  82. void UnwrapCurrentThread();
  83. bool IsMainThread();
  84. private:
  85. ThreadManager();
  86. ~ThreadManager();
  87. #if defined(WEBRTC_POSIX)
  88. pthread_key_t key_;
  89. #endif
  90. #if defined(WEBRTC_WIN)
  91. const DWORD key_;
  92. #endif
  93. // The thread to potentially autowrap.
  94. const PlatformThreadRef main_thread_ref_;
  95. RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
  96. };
  97. struct _SendMessage {
  98. _SendMessage() {}
  99. Thread* thread;
  100. Message msg;
  101. bool* ready;
  102. };
  103. // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
  104. class RTC_EXPORT RTC_LOCKABLE Thread : public MessageQueue {
  105. public:
  106. explicit Thread(SocketServer* ss);
  107. explicit Thread(std::unique_ptr<SocketServer> ss);
  108. // Constructors meant for subclasses; they should call DoInit themselves and
  109. // pass false for |do_init|, so that DoInit is called only on the fully
  110. // instantiated class, which avoids a vptr data race.
  111. Thread(SocketServer* ss, bool do_init);
  112. Thread(std::unique_ptr<SocketServer> ss, bool do_init);
  113. // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
  114. // guarantee Stop() is explicitly called before the subclass is destroyed).
  115. // This is required to avoid a data race between the destructor modifying the
  116. // vtable, and the Thread::PreRun calling the virtual method Run().
  117. ~Thread() override;
  118. static std::unique_ptr<Thread> CreateWithSocketServer();
  119. static std::unique_ptr<Thread> Create();
  120. static Thread* Current();
  121. // Used to catch performance regressions. Use this to disallow blocking calls
  122. // (Invoke) for a given scope. If a synchronous call is made while this is in
  123. // effect, an assert will be triggered.
  124. // Note that this is a single threaded class.
  125. class ScopedDisallowBlockingCalls {
  126. public:
  127. ScopedDisallowBlockingCalls();
  128. ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
  129. ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
  130. delete;
  131. ~ScopedDisallowBlockingCalls();
  132. private:
  133. Thread* const thread_;
  134. const bool previous_state_;
  135. };
  136. bool IsCurrent() const;
  137. // Sleeps the calling thread for the specified number of milliseconds, during
  138. // which time no processing is performed. Returns false if sleeping was
  139. // interrupted by a signal (POSIX only).
  140. static bool SleepMs(int millis);
  141. // Sets the thread's name, for debugging. Must be called before Start().
  142. // If |obj| is non-null, its value is appended to |name|.
  143. const std::string& name() const { return name_; }
  144. bool SetName(const std::string& name, const void* obj);
  145. // Starts the execution of the thread.
  146. bool Start();
  147. // 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. // By default, Thread::Run() calls ProcessMessages(kForever). To do other
  153. // work, override Run(). To receive and dispatch messages, call
  154. // ProcessMessages occasionally.
  155. virtual void Run();
  156. virtual void Send(const Location& posted_from,
  157. MessageHandler* phandler,
  158. uint32_t id = 0,
  159. MessageData* pdata = nullptr);
  160. // Convenience method to invoke a functor on another thread. Caller must
  161. // provide the |ReturnT| template argument, which cannot (easily) be deduced.
  162. // Uses Send() internally, which blocks the current thread until execution
  163. // is complete.
  164. // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
  165. // &MyFunctionReturningBool);
  166. // NOTE: This function can only be called when synchronous calls are allowed.
  167. // See ScopedDisallowBlockingCalls for details.
  168. // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
  169. // be achieved with PostTask() and callbacks instead.
  170. template <class ReturnT, class FunctorT>
  171. ReturnT Invoke(const Location& posted_from, FunctorT&& functor) {
  172. FunctorMessageHandler<ReturnT, FunctorT> handler(
  173. std::forward<FunctorT>(functor));
  174. InvokeInternal(posted_from, &handler);
  175. return handler.MoveResult();
  176. }
  177. // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
  178. // without blocking the thread that invoked PostTask(). Ownership of |functor|
  179. // is passed and (usually, see below) destroyed on |this| thread after it is
  180. // invoked.
  181. // Requirements of FunctorT:
  182. // - FunctorT is movable.
  183. // - FunctorT implements "T operator()()" or "T operator()() const" for some T
  184. // (if T is not void, the return value is discarded on |this| thread).
  185. // - FunctorT has a public destructor that can be invoked from |this| thread
  186. // after operation() has been invoked.
  187. // - The functor must not cause the thread to quit before PostTask() is done.
  188. //
  189. // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
  190. // the task is run, it will be destroyed on |this| thread. However, if there
  191. // are pending tasks by the time the Thread is destroyed, or a task is posted
  192. // to a thread that is quitting, the task is destroyed immediately, on the
  193. // calling thread. Destroying the Thread only blocks for any currently running
  194. // task to complete. Note that TQ abstraction is even vaguer on how
  195. // destruction happens in these cases, allowing destruction to happen
  196. // asynchronously at a later time and on some arbitrary thread. So to ease
  197. // migration, don't depend on Thread::PostTask destroying un-run tasks
  198. // immediately.
  199. //
  200. // Example - Calling a class method:
  201. // class Foo {
  202. // public:
  203. // void DoTheThing();
  204. // };
  205. // Foo foo;
  206. // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
  207. //
  208. // Example - Calling a lambda function:
  209. // thread->PostTask(RTC_FROM_HERE,
  210. // [&x, &y] { x.TrackComputations(y.Compute()); });
  211. template <class FunctorT>
  212. void PostTask(const Location& posted_from, FunctorT&& functor) {
  213. // Allocate at first call, never deallocate.
  214. static auto* const handler =
  215. new rtc_thread_internal::MessageHandlerWithTask;
  216. Post(posted_from, handler, 0,
  217. new rtc_thread_internal::MessageWithFunctor<FunctorT>(
  218. std::forward<FunctorT>(functor)));
  219. }
  220. // From MessageQueue
  221. bool IsProcessingMessagesForTesting() override;
  222. void Clear(MessageHandler* phandler,
  223. uint32_t id = MQID_ANY,
  224. MessageList* removed = nullptr) override;
  225. void ReceiveSends() override;
  226. // ProcessMessages will process I/O and dispatch messages until:
  227. // 1) cms milliseconds have elapsed (returns true)
  228. // 2) Stop() is called (returns false)
  229. bool ProcessMessages(int cms);
  230. // Returns true if this is a thread that we created using the standard
  231. // constructor, false if it was created by a call to
  232. // ThreadManager::WrapCurrentThread(). The main thread of an application
  233. // is generally not owned, since the OS representation of the thread
  234. // obviously exists before we can get to it.
  235. // You cannot call Start on non-owned threads.
  236. bool IsOwned();
  237. // Expose private method IsRunning() for tests.
  238. //
  239. // DANGER: this is a terrible public API. Most callers that might want to
  240. // call this likely do not have enough control/knowledge of the Thread in
  241. // question to guarantee that the returned value remains true for the duration
  242. // of whatever code is conditionally executing because of the return value!
  243. bool RunningForTest() { return IsRunning(); }
  244. // These functions are public to avoid injecting test hooks. Don't call them
  245. // outside of tests.
  246. // This method should be called when thread is created using non standard
  247. // method, like derived implementation of rtc::Thread and it can not be
  248. // started by calling Start(). This will set started flag to true and
  249. // owned to false. This must be called from the current thread.
  250. bool WrapCurrent();
  251. void UnwrapCurrent();
  252. // Sets the per-thread allow-blocking-calls flag to false; this is
  253. // irrevocable. Must be called on this thread.
  254. void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
  255. #ifdef WEBRTC_ANDROID
  256. // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
  257. // invariants upheld by DisallowBlockingCalls() and
  258. // ScopedDisallowBlockingCalls. Must be called on this thread.
  259. void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
  260. #endif
  261. protected:
  262. // Same as WrapCurrent except that it never fails as it does not try to
  263. // acquire the synchronization access of the thread. The caller should never
  264. // call Stop() or Join() on this thread.
  265. void SafeWrapCurrent();
  266. // Blocks the calling thread until this thread has terminated.
  267. void Join();
  268. static void AssertBlockingIsAllowedOnCurrentThread();
  269. friend class ScopedDisallowBlockingCalls;
  270. private:
  271. // Sets the per-thread allow-blocking-calls flag and returns the previous
  272. // value. Must be called on this thread.
  273. bool SetAllowBlockingCalls(bool allow);
  274. #if defined(WEBRTC_WIN)
  275. static DWORD WINAPI PreRun(LPVOID context);
  276. #else
  277. static void* PreRun(void* pv);
  278. #endif
  279. // ThreadManager calls this instead WrapCurrent() because
  280. // ThreadManager::Instance() cannot be used while ThreadManager is
  281. // being created.
  282. // The method tries to get synchronization rights of the thread on Windows if
  283. // |need_synchronize_access| is true.
  284. bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
  285. bool need_synchronize_access);
  286. // Return true if the thread is currently running.
  287. bool IsRunning();
  288. // Processes received "Send" requests. If |source| is not null, only requests
  289. // from |source| are processed, otherwise, all requests are processed.
  290. void ReceiveSendsFromThread(const Thread* source);
  291. // If |source| is not null, pops the first "Send" message from |source| in
  292. // |sendlist_|, otherwise, pops the first "Send" message of |sendlist_|.
  293. // The caller must lock |crit_| before calling.
  294. // Returns true if there is such a message.
  295. bool PopSendMessageFromThread(const Thread* source, _SendMessage* msg);
  296. void InvokeInternal(const Location& posted_from, MessageHandler* handler);
  297. std::list<_SendMessage> sendlist_;
  298. std::string name_;
  299. // TODO(tommi): Add thread checks for proper use of control methods.
  300. // Ideally we should be able to just use PlatformThread.
  301. #if defined(WEBRTC_POSIX)
  302. pthread_t thread_ = 0;
  303. #endif
  304. #if defined(WEBRTC_WIN)
  305. HANDLE thread_ = nullptr;
  306. DWORD thread_id_ = 0;
  307. #endif
  308. // Indicates whether or not ownership of the worker thread lies with
  309. // this instance or not. (i.e. owned_ == !wrapped).
  310. // Must only be modified when the worker thread is not running.
  311. bool owned_ = true;
  312. // Only touched from the worker thread itself.
  313. bool blocking_calls_allowed_ = true;
  314. friend class ThreadManager;
  315. RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
  316. };
  317. // AutoThread automatically installs itself at construction
  318. // uninstalls at destruction, if a Thread object is
  319. // _not already_ associated with the current OS thread.
  320. class AutoThread : public Thread {
  321. public:
  322. AutoThread();
  323. ~AutoThread() override;
  324. private:
  325. RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
  326. };
  327. // AutoSocketServerThread automatically installs itself at
  328. // construction and uninstalls at destruction. If a Thread object is
  329. // already associated with the current OS thread, it is temporarily
  330. // disassociated and restored by the destructor.
  331. class AutoSocketServerThread : public Thread {
  332. public:
  333. explicit AutoSocketServerThread(SocketServer* ss);
  334. ~AutoSocketServerThread() override;
  335. private:
  336. rtc::Thread* old_thread_;
  337. RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
  338. };
  339. } // namespace rtc
  340. #endif // RTC_BASE_THREAD_H_