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.

334 lines
11 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_MESSAGE_QUEUE_H_
  11. #define RTC_BASE_MESSAGE_QUEUE_H_
  12. #include <string.h>
  13. #include <algorithm>
  14. #include <list>
  15. #include <memory>
  16. #include <queue>
  17. #include <vector>
  18. #include "api/scoped_refptr.h"
  19. #include "rtc_base/constructor_magic.h"
  20. #include "rtc_base/critical_section.h"
  21. #include "rtc_base/location.h"
  22. #include "rtc_base/message_handler.h"
  23. #include "rtc_base/socket_server.h"
  24. #include "rtc_base/system/rtc_export.h"
  25. #include "rtc_base/third_party/sigslot/sigslot.h"
  26. #include "rtc_base/thread_annotations.h"
  27. namespace rtc {
  28. struct Message;
  29. class MessageQueue;
  30. // MessageQueueManager does cleanup of of message queues
  31. class RTC_EXPORT MessageQueueManager {
  32. public:
  33. static void Add(MessageQueue* message_queue);
  34. static void Remove(MessageQueue* message_queue);
  35. static void Clear(MessageHandler* handler);
  36. // TODO(nisse): Delete alias, as soon as downstream code is updated.
  37. static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); }
  38. // For testing purposes, for use with a simulated clock.
  39. // Ensures that all message queues have processed delayed messages
  40. // up until the current point in time.
  41. static void ProcessAllMessageQueuesForTesting();
  42. private:
  43. static MessageQueueManager* Instance();
  44. MessageQueueManager();
  45. ~MessageQueueManager();
  46. void AddInternal(MessageQueue* message_queue);
  47. void RemoveInternal(MessageQueue* message_queue);
  48. void ClearInternal(MessageHandler* handler);
  49. void ProcessAllMessageQueuesInternal();
  50. // This list contains all live MessageQueues.
  51. std::vector<MessageQueue*> message_queues_ RTC_GUARDED_BY(crit_);
  52. // Methods that don't modify the list of message queues may be called in a
  53. // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
  54. // calls.
  55. CriticalSection crit_;
  56. size_t processing_ RTC_GUARDED_BY(crit_);
  57. };
  58. // Derive from this for specialized data
  59. // App manages lifetime, except when messages are purged
  60. class MessageData {
  61. public:
  62. MessageData() {}
  63. virtual ~MessageData() {}
  64. };
  65. template <class T>
  66. class TypedMessageData : public MessageData {
  67. public:
  68. explicit TypedMessageData(const T& data) : data_(data) {}
  69. const T& data() const { return data_; }
  70. T& data() { return data_; }
  71. private:
  72. T data_;
  73. };
  74. // Like TypedMessageData, but for pointers that require a delete.
  75. template <class T>
  76. class ScopedMessageData : public MessageData {
  77. public:
  78. explicit ScopedMessageData(std::unique_ptr<T> data)
  79. : data_(std::move(data)) {}
  80. // Deprecated.
  81. // TODO(deadbeef): Remove this once downstream applications stop using it.
  82. explicit ScopedMessageData(T* data) : data_(data) {}
  83. // Deprecated.
  84. // TODO(deadbeef): Returning a reference to a unique ptr? Why. Get rid of
  85. // this once downstream applications stop using it, then rename inner_data to
  86. // just data.
  87. const std::unique_ptr<T>& data() const { return data_; }
  88. std::unique_ptr<T>& data() { return data_; }
  89. const T& inner_data() const { return *data_; }
  90. T& inner_data() { return *data_; }
  91. private:
  92. std::unique_ptr<T> data_;
  93. };
  94. // Like ScopedMessageData, but for reference counted pointers.
  95. template <class T>
  96. class ScopedRefMessageData : public MessageData {
  97. public:
  98. explicit ScopedRefMessageData(T* data) : data_(data) {}
  99. const scoped_refptr<T>& data() const { return data_; }
  100. scoped_refptr<T>& data() { return data_; }
  101. private:
  102. scoped_refptr<T> data_;
  103. };
  104. template <class T>
  105. inline MessageData* WrapMessageData(const T& data) {
  106. return new TypedMessageData<T>(data);
  107. }
  108. template <class T>
  109. inline const T& UseMessageData(MessageData* data) {
  110. return static_cast<TypedMessageData<T>*>(data)->data();
  111. }
  112. template <class T>
  113. class DisposeData : public MessageData {
  114. public:
  115. explicit DisposeData(T* data) : data_(data) {}
  116. virtual ~DisposeData() { delete data_; }
  117. private:
  118. T* data_;
  119. };
  120. const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
  121. const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
  122. // No destructor
  123. struct Message {
  124. Message()
  125. : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
  126. inline bool Match(MessageHandler* handler, uint32_t id) const {
  127. return (handler == nullptr || handler == phandler) &&
  128. (id == MQID_ANY || id == message_id);
  129. }
  130. Location posted_from;
  131. MessageHandler* phandler;
  132. uint32_t message_id;
  133. MessageData* pdata;
  134. int64_t ts_sensitive;
  135. };
  136. typedef std::list<Message> MessageList;
  137. // DelayedMessage goes into a priority queue, sorted by trigger time. Messages
  138. // with the same trigger time are processed in num_ (FIFO) order.
  139. class DelayedMessage {
  140. public:
  141. DelayedMessage(int64_t delay,
  142. int64_t trigger,
  143. uint32_t num,
  144. const Message& msg)
  145. : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
  146. bool operator<(const DelayedMessage& dmsg) const {
  147. return (dmsg.msTrigger_ < msTrigger_) ||
  148. ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
  149. }
  150. int64_t cmsDelay_; // for debugging
  151. int64_t msTrigger_;
  152. uint32_t num_;
  153. Message msg_;
  154. };
  155. class RTC_EXPORT MessageQueue {
  156. public:
  157. static const int kForever = -1;
  158. // Create a new MessageQueue and optionally assign it to the passed
  159. // SocketServer. Subclasses that override Clear should pass false for
  160. // init_queue and call DoInit() from their constructor to prevent races
  161. // with the MessageQueueManager using the object while the vtable is still
  162. // being created.
  163. MessageQueue(SocketServer* ss, bool init_queue);
  164. MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
  165. // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
  166. // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
  167. // between the destructor modifying the vtable, and the MessageQueueManager
  168. // calling Clear on the object from a different thread.
  169. virtual ~MessageQueue();
  170. SocketServer* socketserver();
  171. // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
  172. // futher Posts and Sends will fail. However, any pending Sends and *ready*
  173. // Posts (as opposed to unexpired delayed Posts) will be delivered before
  174. // Get (or Peek) returns false. By guaranteeing delivery of those messages,
  175. // we eliminate the race condition when an MessageHandler and MessageQueue
  176. // may be destroyed independently of each other.
  177. virtual void Quit();
  178. virtual bool IsQuitting();
  179. virtual void Restart();
  180. // Not all message queues actually process messages (such as SignalThread).
  181. // In those cases, it's important to know, before posting, that it won't be
  182. // Processed. Normally, this would be true until IsQuitting() is true.
  183. virtual bool IsProcessingMessagesForTesting();
  184. // Get() will process I/O until:
  185. // 1) A message is available (returns true)
  186. // 2) cmsWait seconds have elapsed (returns false)
  187. // 3) Stop() is called (returns false)
  188. virtual bool Get(Message* pmsg,
  189. int cmsWait = kForever,
  190. bool process_io = true);
  191. virtual bool Peek(Message* pmsg, int cmsWait = 0);
  192. virtual void Post(const Location& posted_from,
  193. MessageHandler* phandler,
  194. uint32_t id = 0,
  195. MessageData* pdata = nullptr,
  196. bool time_sensitive = false);
  197. virtual void PostDelayed(const Location& posted_from,
  198. int cmsDelay,
  199. MessageHandler* phandler,
  200. uint32_t id = 0,
  201. MessageData* pdata = nullptr);
  202. virtual void PostAt(const Location& posted_from,
  203. int64_t tstamp,
  204. MessageHandler* phandler,
  205. uint32_t id = 0,
  206. MessageData* pdata = nullptr);
  207. // TODO(honghaiz): Remove this when all the dependencies are removed.
  208. virtual void PostAt(const Location& posted_from,
  209. uint32_t tstamp,
  210. MessageHandler* phandler,
  211. uint32_t id = 0,
  212. MessageData* pdata = nullptr);
  213. virtual void Clear(MessageHandler* phandler,
  214. uint32_t id = MQID_ANY,
  215. MessageList* removed = nullptr);
  216. virtual void Dispatch(Message* pmsg);
  217. virtual void ReceiveSends();
  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_); // msgq_.size() is not thread safe.
  223. return msgq_.size() + dmsgq_.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. protected:
  236. class PriorityQueue : public std::priority_queue<DelayedMessage> {
  237. public:
  238. container_type& container() { return c; }
  239. void reheap() { make_heap(c.begin(), c.end(), comp); }
  240. };
  241. void DoDelayPost(const Location& posted_from,
  242. int64_t cmsDelay,
  243. int64_t tstamp,
  244. MessageHandler* phandler,
  245. uint32_t id,
  246. MessageData* pdata);
  247. // Perform initialization, subclasses must call this from their constructor
  248. // if false was passed as init_queue to the MessageQueue constructor.
  249. void DoInit();
  250. // Does not take any lock. Must be called either while holding crit_, or by
  251. // the destructor (by definition, the latter has exclusive access).
  252. void ClearInternal(MessageHandler* phandler,
  253. uint32_t id,
  254. MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
  255. // Perform cleanup; subclasses must call this from the destructor,
  256. // and are not expected to actually hold the lock.
  257. void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
  258. void WakeUpSocketServer();
  259. bool fPeekKeep_;
  260. Message msgPeek_;
  261. MessageList msgq_ RTC_GUARDED_BY(crit_);
  262. PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
  263. uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
  264. CriticalSection crit_;
  265. bool fInitialized_;
  266. bool fDestroyed_;
  267. private:
  268. volatile int stop_;
  269. // The SocketServer might not be owned by MessageQueue.
  270. SocketServer* const ss_;
  271. // Used if SocketServer ownership lies with |this|.
  272. std::unique_ptr<SocketServer> own_ss_;
  273. RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
  274. };
  275. } // namespace rtc
  276. #endif // RTC_BASE_MESSAGE_QUEUE_H_