thread.h 23 KB

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