thread.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 <map>
  15. #include <memory>
  16. #include <queue>
  17. #include <set>
  18. #include <string>
  19. #include <type_traits>
  20. #include <vector>
  21. #if defined(WEBRTC_POSIX)
  22. #include <pthread.h>
  23. #endif
  24. #include "api/function_view.h"
  25. #include "api/task_queue/queued_task.h"
  26. #include "api/task_queue/task_queue_base.h"
  27. #include "rtc_base/constructor_magic.h"
  28. #include "rtc_base/deprecated/recursive_critical_section.h"
  29. #include "rtc_base/location.h"
  30. #include "rtc_base/message_handler.h"
  31. #include "rtc_base/platform_thread_types.h"
  32. #include "rtc_base/socket_server.h"
  33. #include "rtc_base/system/rtc_export.h"
  34. #include "rtc_base/thread_annotations.h"
  35. #include "rtc_base/thread_message.h"
  36. #if defined(WEBRTC_WIN)
  37. #include "rtc_base/win32.h"
  38. #endif
  39. namespace rtc {
  40. class Thread;
  41. namespace rtc_thread_internal {
  42. class MessageLikeTask : public MessageData {
  43. public:
  44. virtual void Run() = 0;
  45. };
  46. template <class FunctorT>
  47. class MessageWithFunctor final : public MessageLikeTask {
  48. public:
  49. explicit MessageWithFunctor(FunctorT&& functor)
  50. : functor_(std::forward<FunctorT>(functor)) {}
  51. void Run() override { functor_(); }
  52. private:
  53. ~MessageWithFunctor() override {}
  54. typename std::remove_reference<FunctorT>::type functor_;
  55. RTC_DISALLOW_COPY_AND_ASSIGN(MessageWithFunctor);
  56. };
  57. } // namespace rtc_thread_internal
  58. class RTC_EXPORT ThreadManager {
  59. public:
  60. static const int kForever = -1;
  61. // Singleton, constructor and destructor are private.
  62. static ThreadManager* Instance();
  63. static void Add(Thread* message_queue);
  64. static void Remove(Thread* message_queue);
  65. static void Clear(MessageHandler* handler);
  66. // For testing purposes, for use with a simulated clock.
  67. // Ensures that all message queues have processed delayed messages
  68. // up until the current point in time.
  69. static void ProcessAllMessageQueuesForTesting();
  70. Thread* CurrentThread();
  71. void SetCurrentThread(Thread* thread);
  72. // Allows changing the current thread, this is intended for tests where we
  73. // want to simulate multiple threads running on a single physical thread.
  74. void ChangeCurrentThreadForTest(Thread* thread);
  75. // Returns a thread object with its thread_ ivar set
  76. // to whatever the OS uses to represent the thread.
  77. // If there already *is* a Thread object corresponding to this thread,
  78. // this method will return that. Otherwise it creates a new Thread
  79. // object whose wrapped() method will return true, and whose
  80. // handle will, on Win32, be opened with only synchronization privileges -
  81. // if you need more privilegs, rather than changing this method, please
  82. // write additional code to adjust the privileges, or call a different
  83. // factory method of your own devising, because this one gets used in
  84. // unexpected contexts (like inside browser plugins) and it would be a
  85. // shame to break it. It is also conceivable on Win32 that we won't even
  86. // be able to get synchronization privileges, in which case the result
  87. // will have a null handle.
  88. Thread* WrapCurrentThread();
  89. void UnwrapCurrentThread();
  90. bool IsMainThread();
  91. #if RTC_DCHECK_IS_ON
  92. // Registers that a Send operation is to be performed between |source| and
  93. // |target|, while checking that this does not cause a send cycle that could
  94. // potentially cause a deadlock.
  95. void RegisterSendAndCheckForCycles(Thread* source, Thread* target);
  96. #endif
  97. private:
  98. ThreadManager();
  99. ~ThreadManager();
  100. void SetCurrentThreadInternal(Thread* thread);
  101. void AddInternal(Thread* message_queue);
  102. void RemoveInternal(Thread* message_queue);
  103. void ClearInternal(MessageHandler* handler);
  104. void ProcessAllMessageQueuesInternal();
  105. #if RTC_DCHECK_IS_ON
  106. void RemoveFromSendGraph(Thread* thread) RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
  107. #endif
  108. // This list contains all live Threads.
  109. std::vector<Thread*> message_queues_ RTC_GUARDED_BY(crit_);
  110. // Methods that don't modify the list of message queues may be called in a
  111. // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
  112. // calls.
  113. RecursiveCriticalSection crit_;
  114. size_t processing_ RTC_GUARDED_BY(crit_) = 0;
  115. #if RTC_DCHECK_IS_ON
  116. // Represents all thread seand actions by storing all send targets per thread.
  117. // This is used by RegisterSendAndCheckForCycles. This graph has no cycles
  118. // since we will trigger a CHECK failure if a cycle is introduced.
  119. std::map<Thread*, std::set<Thread*>> send_graph_ RTC_GUARDED_BY(crit_);
  120. #endif
  121. #if defined(WEBRTC_POSIX)
  122. pthread_key_t key_;
  123. #endif
  124. #if defined(WEBRTC_WIN)
  125. const DWORD key_;
  126. #endif
  127. // The thread to potentially autowrap.
  128. const PlatformThreadRef main_thread_ref_;
  129. RTC_DISALLOW_COPY_AND_ASSIGN(ThreadManager);
  130. };
  131. // WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread().
  132. class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase {
  133. public:
  134. static const int kForever = -1;
  135. // Create a new Thread and optionally assign it to the passed
  136. // SocketServer. Subclasses that override Clear should pass false for
  137. // init_queue and call DoInit() from their constructor to prevent races
  138. // with the ThreadManager using the object while the vtable is still
  139. // being created.
  140. explicit Thread(SocketServer* ss);
  141. explicit Thread(std::unique_ptr<SocketServer> ss);
  142. // Constructors meant for subclasses; they should call DoInit themselves and
  143. // pass false for |do_init|, so that DoInit is called only on the fully
  144. // instantiated class, which avoids a vptr data race.
  145. Thread(SocketServer* ss, bool do_init);
  146. Thread(std::unique_ptr<SocketServer> ss, bool do_init);
  147. // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or
  148. // guarantee Stop() is explicitly called before the subclass is destroyed).
  149. // This is required to avoid a data race between the destructor modifying the
  150. // vtable, and the Thread::PreRun calling the virtual method Run().
  151. // NOTE: SUBCLASSES OF Thread THAT OVERRIDE Clear MUST CALL
  152. // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
  153. // between the destructor modifying the vtable, and the ThreadManager
  154. // calling Clear on the object from a different thread.
  155. ~Thread() override;
  156. static std::unique_ptr<Thread> CreateWithSocketServer();
  157. static std::unique_ptr<Thread> Create();
  158. static Thread* Current();
  159. // Used to catch performance regressions. Use this to disallow blocking calls
  160. // (Invoke) for a given scope. If a synchronous call is made while this is in
  161. // effect, an assert will be triggered.
  162. // Note that this is a single threaded class.
  163. class ScopedDisallowBlockingCalls {
  164. public:
  165. ScopedDisallowBlockingCalls();
  166. ScopedDisallowBlockingCalls(const ScopedDisallowBlockingCalls&) = delete;
  167. ScopedDisallowBlockingCalls& operator=(const ScopedDisallowBlockingCalls&) =
  168. delete;
  169. ~ScopedDisallowBlockingCalls();
  170. private:
  171. Thread* const thread_;
  172. const bool previous_state_;
  173. };
  174. SocketServer* socketserver();
  175. // Note: The behavior of Thread has changed. When a thread is stopped,
  176. // futher Posts and Sends will fail. However, any pending Sends and *ready*
  177. // Posts (as opposed to unexpired delayed Posts) will be delivered before
  178. // Get (or Peek) returns false. By guaranteeing delivery of those messages,
  179. // we eliminate the race condition when an MessageHandler and Thread
  180. // may be destroyed independently of each other.
  181. virtual void Quit();
  182. virtual bool IsQuitting();
  183. virtual void Restart();
  184. // Not all message queues actually process messages (such as SignalThread).
  185. // In those cases, it's important to know, before posting, that it won't be
  186. // Processed. Normally, this would be true until IsQuitting() is true.
  187. virtual bool IsProcessingMessagesForTesting();
  188. // Get() will process I/O until:
  189. // 1) A message is available (returns true)
  190. // 2) cmsWait seconds have elapsed (returns false)
  191. // 3) Stop() is called (returns false)
  192. virtual bool Get(Message* pmsg,
  193. int cmsWait = kForever,
  194. bool process_io = true);
  195. virtual bool Peek(Message* pmsg, int cmsWait = 0);
  196. // |time_sensitive| is deprecated and should always be false.
  197. virtual void Post(const Location& posted_from,
  198. MessageHandler* phandler,
  199. uint32_t id = 0,
  200. MessageData* pdata = nullptr,
  201. bool time_sensitive = false);
  202. virtual void PostDelayed(const Location& posted_from,
  203. int delay_ms,
  204. MessageHandler* phandler,
  205. uint32_t id = 0,
  206. MessageData* pdata = nullptr);
  207. virtual void PostAt(const Location& posted_from,
  208. int64_t run_at_ms,
  209. MessageHandler* phandler,
  210. uint32_t id = 0,
  211. MessageData* pdata = nullptr);
  212. virtual void Clear(MessageHandler* phandler,
  213. uint32_t id = MQID_ANY,
  214. MessageList* removed = nullptr);
  215. virtual void Dispatch(Message* pmsg);
  216. // Amount of time until the next message can be retrieved
  217. virtual int GetDelay();
  218. bool empty() const { return size() == 0u; }
  219. size_t size() const {
  220. CritScope cs(&crit_);
  221. return messages_.size() + delayed_messages_.size() + (fPeekKeep_ ? 1u : 0u);
  222. }
  223. // Internally posts a message which causes the doomed object to be deleted
  224. template <class T>
  225. void Dispose(T* doomed) {
  226. if (doomed) {
  227. Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
  228. }
  229. }
  230. // When this signal is sent out, any references to this queue should
  231. // no longer be used.
  232. sigslot::signal0<> SignalQueueDestroyed;
  233. bool IsCurrent() const;
  234. // Sleeps the calling thread for the specified number of milliseconds, during
  235. // which time no processing is performed. Returns false if sleeping was
  236. // interrupted by a signal (POSIX only).
  237. static bool SleepMs(int millis);
  238. // Sets the thread's name, for debugging. Must be called before Start().
  239. // If |obj| is non-null, its value is appended to |name|.
  240. const std::string& name() const { return name_; }
  241. bool SetName(const std::string& name, const void* obj);
  242. // Starts the execution of the thread.
  243. bool Start();
  244. // Tells the thread to stop and waits until it is joined.
  245. // Never call Stop on the current thread. Instead use the inherited Quit
  246. // function which will exit the base Thread without terminating the
  247. // underlying OS thread.
  248. virtual void Stop();
  249. // By default, Thread::Run() calls ProcessMessages(kForever). To do other
  250. // work, override Run(). To receive and dispatch messages, call
  251. // ProcessMessages occasionally.
  252. virtual void Run();
  253. virtual void Send(const Location& posted_from,
  254. MessageHandler* phandler,
  255. uint32_t id = 0,
  256. MessageData* pdata = nullptr);
  257. // Convenience method to invoke a functor on another thread. Caller must
  258. // provide the |ReturnT| template argument, which cannot (easily) be deduced.
  259. // Uses Send() internally, which blocks the current thread until execution
  260. // is complete.
  261. // Ex: bool result = thread.Invoke<bool>(RTC_FROM_HERE,
  262. // &MyFunctionReturningBool);
  263. // NOTE: This function can only be called when synchronous calls are allowed.
  264. // See ScopedDisallowBlockingCalls for details.
  265. // NOTE: Blocking invokes are DISCOURAGED, consider if what you're doing can
  266. // be achieved with PostTask() and callbacks instead.
  267. template <
  268. class ReturnT,
  269. typename = typename std::enable_if<!std::is_void<ReturnT>::value>::type>
  270. ReturnT Invoke(const Location& posted_from, FunctionView<ReturnT()> functor) {
  271. ReturnT result;
  272. InvokeInternal(posted_from, [functor, &result] { result = functor(); });
  273. return result;
  274. }
  275. template <
  276. class ReturnT,
  277. typename = typename std::enable_if<std::is_void<ReturnT>::value>::type>
  278. void Invoke(const Location& posted_from, FunctionView<void()> functor) {
  279. InvokeInternal(posted_from, functor);
  280. }
  281. // Allows invoke to specified |thread|. Thread never will be dereferenced and
  282. // will be used only for reference-based comparison, so instance can be safely
  283. // deleted. If NDEBUG is defined and DCHECK_ALWAYS_ON is undefined do nothing.
  284. void AllowInvokesToThread(Thread* thread);
  285. // If NDEBUG is defined and DCHECK_ALWAYS_ON is undefined do nothing.
  286. void DisallowAllInvokes();
  287. // Returns true if |target| was allowed by AllowInvokesToThread() or if no
  288. // calls were made to AllowInvokesToThread and DisallowAllInvokes. Otherwise
  289. // returns false.
  290. // If NDEBUG is defined and DCHECK_ALWAYS_ON is undefined always returns true.
  291. bool IsInvokeToThreadAllowed(rtc::Thread* target);
  292. // Posts a task to invoke the functor on |this| thread asynchronously, i.e.
  293. // without blocking the thread that invoked PostTask(). Ownership of |functor|
  294. // is passed and (usually, see below) destroyed on |this| thread after it is
  295. // invoked.
  296. // Requirements of FunctorT:
  297. // - FunctorT is movable.
  298. // - FunctorT implements "T operator()()" or "T operator()() const" for some T
  299. // (if T is not void, the return value is discarded on |this| thread).
  300. // - FunctorT has a public destructor that can be invoked from |this| thread
  301. // after operation() has been invoked.
  302. // - The functor must not cause the thread to quit before PostTask() is done.
  303. //
  304. // Destruction of the functor/task mimics what TaskQueue::PostTask does: If
  305. // the task is run, it will be destroyed on |this| thread. However, if there
  306. // are pending tasks by the time the Thread is destroyed, or a task is posted
  307. // to a thread that is quitting, the task is destroyed immediately, on the
  308. // calling thread. Destroying the Thread only blocks for any currently running
  309. // task to complete. Note that TQ abstraction is even vaguer on how
  310. // destruction happens in these cases, allowing destruction to happen
  311. // asynchronously at a later time and on some arbitrary thread. So to ease
  312. // migration, don't depend on Thread::PostTask destroying un-run tasks
  313. // immediately.
  314. //
  315. // Example - Calling a class method:
  316. // class Foo {
  317. // public:
  318. // void DoTheThing();
  319. // };
  320. // Foo foo;
  321. // thread->PostTask(RTC_FROM_HERE, Bind(&Foo::DoTheThing, &foo));
  322. //
  323. // Example - Calling a lambda function:
  324. // thread->PostTask(RTC_FROM_HERE,
  325. // [&x, &y] { x.TrackComputations(y.Compute()); });
  326. template <class FunctorT>
  327. void PostTask(const Location& posted_from, FunctorT&& functor) {
  328. Post(posted_from, GetPostTaskMessageHandler(), /*id=*/0,
  329. new rtc_thread_internal::MessageWithFunctor<FunctorT>(
  330. std::forward<FunctorT>(functor)));
  331. }
  332. template <class FunctorT>
  333. void PostDelayedTask(const Location& posted_from,
  334. FunctorT&& functor,
  335. uint32_t milliseconds) {
  336. PostDelayed(posted_from, milliseconds, GetPostTaskMessageHandler(),
  337. /*id=*/0,
  338. new rtc_thread_internal::MessageWithFunctor<FunctorT>(
  339. std::forward<FunctorT>(functor)));
  340. }
  341. // From TaskQueueBase
  342. void PostTask(std::unique_ptr<webrtc::QueuedTask> task) override;
  343. void PostDelayedTask(std::unique_ptr<webrtc::QueuedTask> task,
  344. uint32_t milliseconds) override;
  345. void Delete() override;
  346. // ProcessMessages will process I/O and dispatch messages until:
  347. // 1) cms milliseconds have elapsed (returns true)
  348. // 2) Stop() is called (returns false)
  349. bool ProcessMessages(int cms);
  350. // Returns true if this is a thread that we created using the standard
  351. // constructor, false if it was created by a call to
  352. // ThreadManager::WrapCurrentThread(). The main thread of an application
  353. // is generally not owned, since the OS representation of the thread
  354. // obviously exists before we can get to it.
  355. // You cannot call Start on non-owned threads.
  356. bool IsOwned();
  357. // Expose private method IsRunning() for tests.
  358. //
  359. // DANGER: this is a terrible public API. Most callers that might want to
  360. // call this likely do not have enough control/knowledge of the Thread in
  361. // question to guarantee that the returned value remains true for the duration
  362. // of whatever code is conditionally executing because of the return value!
  363. bool RunningForTest() { return IsRunning(); }
  364. // These functions are public to avoid injecting test hooks. Don't call them
  365. // outside of tests.
  366. // This method should be called when thread is created using non standard
  367. // method, like derived implementation of rtc::Thread and it can not be
  368. // started by calling Start(). This will set started flag to true and
  369. // owned to false. This must be called from the current thread.
  370. bool WrapCurrent();
  371. void UnwrapCurrent();
  372. // Sets the per-thread allow-blocking-calls flag to false; this is
  373. // irrevocable. Must be called on this thread.
  374. void DisallowBlockingCalls() { SetAllowBlockingCalls(false); }
  375. #ifdef WEBRTC_ANDROID
  376. // Sets the per-thread allow-blocking-calls flag to true, sidestepping the
  377. // invariants upheld by DisallowBlockingCalls() and
  378. // ScopedDisallowBlockingCalls. Must be called on this thread.
  379. void DEPRECATED_AllowBlockingCalls() { SetAllowBlockingCalls(true); }
  380. #endif
  381. protected:
  382. class CurrentThreadSetter : CurrentTaskQueueSetter {
  383. public:
  384. explicit CurrentThreadSetter(Thread* thread)
  385. : CurrentTaskQueueSetter(thread),
  386. manager_(rtc::ThreadManager::Instance()),
  387. previous_(manager_->CurrentThread()) {
  388. manager_->ChangeCurrentThreadForTest(thread);
  389. }
  390. ~CurrentThreadSetter() { manager_->ChangeCurrentThreadForTest(previous_); }
  391. private:
  392. rtc::ThreadManager* const manager_;
  393. rtc::Thread* const previous_;
  394. };
  395. // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
  396. // with the same trigger time are processed in num_ (FIFO) order.
  397. class DelayedMessage {
  398. public:
  399. DelayedMessage(int64_t delay,
  400. int64_t run_time_ms,
  401. uint32_t num,
  402. const Message& msg)
  403. : delay_ms_(delay),
  404. run_time_ms_(run_time_ms),
  405. message_number_(num),
  406. msg_(msg) {}
  407. bool operator<(const DelayedMessage& dmsg) const {
  408. return (dmsg.run_time_ms_ < run_time_ms_) ||
  409. ((dmsg.run_time_ms_ == run_time_ms_) &&
  410. (dmsg.message_number_ < message_number_));
  411. }
  412. int64_t delay_ms_; // for debugging
  413. int64_t run_time_ms_;
  414. // Monotonicaly incrementing number used for ordering of messages
  415. // targeted to execute at the same time.
  416. uint32_t message_number_;
  417. Message msg_;
  418. };
  419. class PriorityQueue : public std::priority_queue<DelayedMessage> {
  420. public:
  421. container_type& container() { return c; }
  422. void reheap() { make_heap(c.begin(), c.end(), comp); }
  423. };
  424. void DoDelayPost(const Location& posted_from,
  425. int64_t cmsDelay,
  426. int64_t tstamp,
  427. MessageHandler* phandler,
  428. uint32_t id,
  429. MessageData* pdata);
  430. // Perform initialization, subclasses must call this from their constructor
  431. // if false was passed as init_queue to the Thread constructor.
  432. void DoInit();
  433. // Does not take any lock. Must be called either while holding crit_, or by
  434. // the destructor (by definition, the latter has exclusive access).
  435. void ClearInternal(MessageHandler* phandler,
  436. uint32_t id,
  437. MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
  438. // Perform cleanup; subclasses must call this from the destructor,
  439. // and are not expected to actually hold the lock.
  440. void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
  441. void WakeUpSocketServer();
  442. // Same as WrapCurrent except that it never fails as it does not try to
  443. // acquire the synchronization access of the thread. The caller should never
  444. // call Stop() or Join() on this thread.
  445. void SafeWrapCurrent();
  446. // Blocks the calling thread until this thread has terminated.
  447. void Join();
  448. static void AssertBlockingIsAllowedOnCurrentThread();
  449. friend class ScopedDisallowBlockingCalls;
  450. RecursiveCriticalSection* CritForTest() { return &crit_; }
  451. private:
  452. class QueuedTaskHandler final : public MessageHandler {
  453. public:
  454. QueuedTaskHandler() {}
  455. void OnMessage(Message* msg) override;
  456. };
  457. // Sets the per-thread allow-blocking-calls flag and returns the previous
  458. // value. Must be called on this thread.
  459. bool SetAllowBlockingCalls(bool allow);
  460. #if defined(WEBRTC_WIN)
  461. static DWORD WINAPI PreRun(LPVOID context);
  462. #else
  463. static void* PreRun(void* pv);
  464. #endif
  465. // ThreadManager calls this instead WrapCurrent() because
  466. // ThreadManager::Instance() cannot be used while ThreadManager is
  467. // being created.
  468. // The method tries to get synchronization rights of the thread on Windows if
  469. // |need_synchronize_access| is true.
  470. bool WrapCurrentWithThreadManager(ThreadManager* thread_manager,
  471. bool need_synchronize_access);
  472. // Return true if the thread is currently running.
  473. bool IsRunning();
  474. void InvokeInternal(const Location& posted_from,
  475. rtc::FunctionView<void()> functor);
  476. // Called by the ThreadManager when being set as the current thread.
  477. void EnsureIsCurrentTaskQueue();
  478. // Called by the ThreadManager when being unset as the current thread.
  479. void ClearCurrentTaskQueue();
  480. // Returns a static-lifetime MessageHandler which runs message with
  481. // MessageLikeTask payload data.
  482. static MessageHandler* GetPostTaskMessageHandler();
  483. bool fPeekKeep_;
  484. Message msgPeek_;
  485. MessageList messages_ RTC_GUARDED_BY(crit_);
  486. PriorityQueue delayed_messages_ RTC_GUARDED_BY(crit_);
  487. uint32_t delayed_next_num_ RTC_GUARDED_BY(crit_);
  488. #if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
  489. std::vector<Thread*> allowed_threads_ RTC_GUARDED_BY(this);
  490. bool invoke_policy_enabled_ RTC_GUARDED_BY(this) = false;
  491. #endif
  492. RecursiveCriticalSection crit_;
  493. bool fInitialized_;
  494. bool fDestroyed_;
  495. volatile int stop_;
  496. // The SocketServer might not be owned by Thread.
  497. SocketServer* const ss_;
  498. // Used if SocketServer ownership lies with |this|.
  499. std::unique_ptr<SocketServer> own_ss_;
  500. std::string name_;
  501. // TODO(tommi): Add thread checks for proper use of control methods.
  502. // Ideally we should be able to just use PlatformThread.
  503. #if defined(WEBRTC_POSIX)
  504. pthread_t thread_ = 0;
  505. #endif
  506. #if defined(WEBRTC_WIN)
  507. HANDLE thread_ = nullptr;
  508. DWORD thread_id_ = 0;
  509. #endif
  510. // Indicates whether or not ownership of the worker thread lies with
  511. // this instance or not. (i.e. owned_ == !wrapped).
  512. // Must only be modified when the worker thread is not running.
  513. bool owned_ = true;
  514. // Only touched from the worker thread itself.
  515. bool blocking_calls_allowed_ = true;
  516. // Runs webrtc::QueuedTask posted to the Thread.
  517. QueuedTaskHandler queued_task_handler_;
  518. std::unique_ptr<TaskQueueBase::CurrentTaskQueueSetter>
  519. task_queue_registration_;
  520. friend class ThreadManager;
  521. RTC_DISALLOW_COPY_AND_ASSIGN(Thread);
  522. };
  523. // AutoThread automatically installs itself at construction
  524. // uninstalls at destruction, if a Thread object is
  525. // _not already_ associated with the current OS thread.
  526. //
  527. // NOTE: *** This class should only be used by tests ***
  528. //
  529. class AutoThread : public Thread {
  530. public:
  531. AutoThread();
  532. ~AutoThread() override;
  533. private:
  534. RTC_DISALLOW_COPY_AND_ASSIGN(AutoThread);
  535. };
  536. // AutoSocketServerThread automatically installs itself at
  537. // construction and uninstalls at destruction. If a Thread object is
  538. // already associated with the current OS thread, it is temporarily
  539. // disassociated and restored by the destructor.
  540. class AutoSocketServerThread : public Thread {
  541. public:
  542. explicit AutoSocketServerThread(SocketServer* ss);
  543. ~AutoSocketServerThread() override;
  544. private:
  545. rtc::Thread* old_thread_;
  546. RTC_DISALLOW_COPY_AND_ASSIGN(AutoSocketServerThread);
  547. };
  548. } // namespace rtc
  549. #endif // RTC_BASE_THREAD_H_