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.

524 lines
15 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. #include "rtc_base/message_queue.h"
  11. #include <string>
  12. #include <utility>
  13. #include "absl/algorithm/container.h"
  14. #include "rtc_base/atomic_ops.h"
  15. #include "rtc_base/checks.h"
  16. #include "rtc_base/logging.h"
  17. #include "rtc_base/thread.h"
  18. #include "rtc_base/time_utils.h"
  19. #include "rtc_base/trace_event.h"
  20. namespace rtc {
  21. namespace {
  22. const int kMaxMsgLatency = 150; // 150 ms
  23. const int kSlowDispatchLoggingThreshold = 50; // 50 ms
  24. class RTC_SCOPED_LOCKABLE MarkProcessingCritScope {
  25. public:
  26. MarkProcessingCritScope(const CriticalSection* cs, size_t* processing)
  27. RTC_EXCLUSIVE_LOCK_FUNCTION(cs)
  28. : cs_(cs), processing_(processing) {
  29. cs_->Enter();
  30. *processing_ += 1;
  31. }
  32. ~MarkProcessingCritScope() RTC_UNLOCK_FUNCTION() {
  33. *processing_ -= 1;
  34. cs_->Leave();
  35. }
  36. private:
  37. const CriticalSection* const cs_;
  38. size_t* processing_;
  39. RTC_DISALLOW_COPY_AND_ASSIGN(MarkProcessingCritScope);
  40. };
  41. } // namespace
  42. //------------------------------------------------------------------
  43. // MessageQueueManager
  44. MessageQueueManager* MessageQueueManager::Instance() {
  45. static MessageQueueManager* const instance = new MessageQueueManager;
  46. return instance;
  47. }
  48. MessageQueueManager::MessageQueueManager() : processing_(0) {}
  49. MessageQueueManager::~MessageQueueManager() {}
  50. void MessageQueueManager::Add(MessageQueue* message_queue) {
  51. return Instance()->AddInternal(message_queue);
  52. }
  53. void MessageQueueManager::AddInternal(MessageQueue* message_queue) {
  54. CritScope cs(&crit_);
  55. // Prevent changes while the list of message queues is processed.
  56. RTC_DCHECK_EQ(processing_, 0);
  57. message_queues_.push_back(message_queue);
  58. }
  59. void MessageQueueManager::Remove(MessageQueue* message_queue) {
  60. return Instance()->RemoveInternal(message_queue);
  61. }
  62. void MessageQueueManager::RemoveInternal(MessageQueue* message_queue) {
  63. {
  64. CritScope cs(&crit_);
  65. // Prevent changes while the list of message queues is processed.
  66. RTC_DCHECK_EQ(processing_, 0);
  67. std::vector<MessageQueue*>::iterator iter;
  68. iter = absl::c_find(message_queues_, message_queue);
  69. if (iter != message_queues_.end()) {
  70. message_queues_.erase(iter);
  71. }
  72. }
  73. }
  74. void MessageQueueManager::Clear(MessageHandler* handler) {
  75. return Instance()->ClearInternal(handler);
  76. }
  77. void MessageQueueManager::ClearInternal(MessageHandler* handler) {
  78. // Deleted objects may cause re-entrant calls to ClearInternal. This is
  79. // allowed as the list of message queues does not change while queues are
  80. // cleared.
  81. MarkProcessingCritScope cs(&crit_, &processing_);
  82. for (MessageQueue* queue : message_queues_) {
  83. queue->Clear(handler);
  84. }
  85. }
  86. void MessageQueueManager::ProcessAllMessageQueuesForTesting() {
  87. return Instance()->ProcessAllMessageQueuesInternal();
  88. }
  89. void MessageQueueManager::ProcessAllMessageQueuesInternal() {
  90. // This works by posting a delayed message at the current time and waiting
  91. // for it to be dispatched on all queues, which will ensure that all messages
  92. // that came before it were also dispatched.
  93. volatile int queues_not_done = 0;
  94. // This class is used so that whether the posted message is processed, or the
  95. // message queue is simply cleared, queues_not_done gets decremented.
  96. class ScopedIncrement : public MessageData {
  97. public:
  98. ScopedIncrement(volatile int* value) : value_(value) {
  99. AtomicOps::Increment(value_);
  100. }
  101. ~ScopedIncrement() override { AtomicOps::Decrement(value_); }
  102. private:
  103. volatile int* value_;
  104. };
  105. {
  106. MarkProcessingCritScope cs(&crit_, &processing_);
  107. for (MessageQueue* queue : message_queues_) {
  108. if (!queue->IsProcessingMessagesForTesting()) {
  109. // If the queue is not processing messages, it can
  110. // be ignored. If we tried to post a message to it, it would be dropped
  111. // or ignored.
  112. continue;
  113. }
  114. queue->PostDelayed(RTC_FROM_HERE, 0, nullptr, MQID_DISPOSE,
  115. new ScopedIncrement(&queues_not_done));
  116. }
  117. }
  118. rtc::Thread* current = rtc::Thread::Current();
  119. // Note: One of the message queues may have been on this thread, which is
  120. // why we can't synchronously wait for queues_not_done to go to 0; we need
  121. // to process messages as well.
  122. while (AtomicOps::AcquireLoad(&queues_not_done) > 0) {
  123. if (current) {
  124. current->ProcessMessages(0);
  125. }
  126. }
  127. }
  128. //------------------------------------------------------------------
  129. // MessageQueue
  130. MessageQueue::MessageQueue(SocketServer* ss, bool init_queue)
  131. : fPeekKeep_(false),
  132. dmsgq_next_num_(0),
  133. fInitialized_(false),
  134. fDestroyed_(false),
  135. stop_(0),
  136. ss_(ss) {
  137. RTC_DCHECK(ss);
  138. // Currently, MessageQueue holds a socket server, and is the base class for
  139. // Thread. It seems like it makes more sense for Thread to hold the socket
  140. // server, and provide it to the MessageQueue, since the Thread controls
  141. // the I/O model, and MQ is agnostic to those details. Anyway, this causes
  142. // messagequeue_unittest to depend on network libraries... yuck.
  143. ss_->SetMessageQueue(this);
  144. if (init_queue) {
  145. DoInit();
  146. }
  147. }
  148. MessageQueue::MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue)
  149. : MessageQueue(ss.get(), init_queue) {
  150. own_ss_ = std::move(ss);
  151. }
  152. MessageQueue::~MessageQueue() {
  153. DoDestroy();
  154. }
  155. void MessageQueue::DoInit() {
  156. if (fInitialized_) {
  157. return;
  158. }
  159. fInitialized_ = true;
  160. MessageQueueManager::Add(this);
  161. }
  162. void MessageQueue::DoDestroy() {
  163. if (fDestroyed_) {
  164. return;
  165. }
  166. fDestroyed_ = true;
  167. // The signal is done from here to ensure
  168. // that it always gets called when the queue
  169. // is going away.
  170. SignalQueueDestroyed();
  171. MessageQueueManager::Remove(this);
  172. ClearInternal(nullptr, MQID_ANY, nullptr);
  173. if (ss_) {
  174. ss_->SetMessageQueue(nullptr);
  175. }
  176. }
  177. SocketServer* MessageQueue::socketserver() {
  178. return ss_;
  179. }
  180. void MessageQueue::WakeUpSocketServer() {
  181. ss_->WakeUp();
  182. }
  183. void MessageQueue::Quit() {
  184. AtomicOps::ReleaseStore(&stop_, 1);
  185. WakeUpSocketServer();
  186. }
  187. bool MessageQueue::IsQuitting() {
  188. return AtomicOps::AcquireLoad(&stop_) != 0;
  189. }
  190. bool MessageQueue::IsProcessingMessagesForTesting() {
  191. return !IsQuitting();
  192. }
  193. void MessageQueue::Restart() {
  194. AtomicOps::ReleaseStore(&stop_, 0);
  195. }
  196. bool MessageQueue::Peek(Message* pmsg, int cmsWait) {
  197. if (fPeekKeep_) {
  198. *pmsg = msgPeek_;
  199. return true;
  200. }
  201. if (!Get(pmsg, cmsWait))
  202. return false;
  203. msgPeek_ = *pmsg;
  204. fPeekKeep_ = true;
  205. return true;
  206. }
  207. bool MessageQueue::Get(Message* pmsg, int cmsWait, bool process_io) {
  208. // Return and clear peek if present
  209. // Always return the peek if it exists so there is Peek/Get symmetry
  210. if (fPeekKeep_) {
  211. *pmsg = msgPeek_;
  212. fPeekKeep_ = false;
  213. return true;
  214. }
  215. // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
  216. int64_t cmsTotal = cmsWait;
  217. int64_t cmsElapsed = 0;
  218. int64_t msStart = TimeMillis();
  219. int64_t msCurrent = msStart;
  220. while (true) {
  221. // Check for sent messages
  222. ReceiveSends();
  223. // Check for posted events
  224. int64_t cmsDelayNext = kForever;
  225. bool first_pass = true;
  226. while (true) {
  227. // All queue operations need to be locked, but nothing else in this loop
  228. // (specifically handling disposed message) can happen inside the crit.
  229. // Otherwise, disposed MessageHandlers will cause deadlocks.
  230. {
  231. CritScope cs(&crit_);
  232. // On the first pass, check for delayed messages that have been
  233. // triggered and calculate the next trigger time.
  234. if (first_pass) {
  235. first_pass = false;
  236. while (!dmsgq_.empty()) {
  237. if (msCurrent < dmsgq_.top().msTrigger_) {
  238. cmsDelayNext = TimeDiff(dmsgq_.top().msTrigger_, msCurrent);
  239. break;
  240. }
  241. msgq_.push_back(dmsgq_.top().msg_);
  242. dmsgq_.pop();
  243. }
  244. }
  245. // Pull a message off the message queue, if available.
  246. if (msgq_.empty()) {
  247. break;
  248. } else {
  249. *pmsg = msgq_.front();
  250. msgq_.pop_front();
  251. }
  252. } // crit_ is released here.
  253. // Log a warning for time-sensitive messages that we're late to deliver.
  254. if (pmsg->ts_sensitive) {
  255. int64_t delay = TimeDiff(msCurrent, pmsg->ts_sensitive);
  256. if (delay > 0) {
  257. RTC_LOG_F(LS_WARNING)
  258. << "id: " << pmsg->message_id
  259. << " delay: " << (delay + kMaxMsgLatency) << "ms";
  260. }
  261. }
  262. // If this was a dispose message, delete it and skip it.
  263. if (MQID_DISPOSE == pmsg->message_id) {
  264. RTC_DCHECK(nullptr == pmsg->phandler);
  265. delete pmsg->pdata;
  266. *pmsg = Message();
  267. continue;
  268. }
  269. return true;
  270. }
  271. if (IsQuitting())
  272. break;
  273. // Which is shorter, the delay wait or the asked wait?
  274. int64_t cmsNext;
  275. if (cmsWait == kForever) {
  276. cmsNext = cmsDelayNext;
  277. } else {
  278. cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
  279. if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
  280. cmsNext = cmsDelayNext;
  281. }
  282. {
  283. // Wait and multiplex in the meantime
  284. if (!ss_->Wait(static_cast<int>(cmsNext), process_io))
  285. return false;
  286. }
  287. // If the specified timeout expired, return
  288. msCurrent = TimeMillis();
  289. cmsElapsed = TimeDiff(msCurrent, msStart);
  290. if (cmsWait != kForever) {
  291. if (cmsElapsed >= cmsWait)
  292. return false;
  293. }
  294. }
  295. return false;
  296. }
  297. void MessageQueue::ReceiveSends() {}
  298. void MessageQueue::Post(const Location& posted_from,
  299. MessageHandler* phandler,
  300. uint32_t id,
  301. MessageData* pdata,
  302. bool time_sensitive) {
  303. if (IsQuitting()) {
  304. delete pdata;
  305. return;
  306. }
  307. // Keep thread safe
  308. // Add the message to the end of the queue
  309. // Signal for the multiplexer to return
  310. {
  311. CritScope cs(&crit_);
  312. Message msg;
  313. msg.posted_from = posted_from;
  314. msg.phandler = phandler;
  315. msg.message_id = id;
  316. msg.pdata = pdata;
  317. if (time_sensitive) {
  318. msg.ts_sensitive = TimeMillis() + kMaxMsgLatency;
  319. }
  320. msgq_.push_back(msg);
  321. }
  322. WakeUpSocketServer();
  323. }
  324. void MessageQueue::PostDelayed(const Location& posted_from,
  325. int cmsDelay,
  326. MessageHandler* phandler,
  327. uint32_t id,
  328. MessageData* pdata) {
  329. return DoDelayPost(posted_from, cmsDelay, TimeAfter(cmsDelay), phandler, id,
  330. pdata);
  331. }
  332. void MessageQueue::PostAt(const Location& posted_from,
  333. uint32_t tstamp,
  334. MessageHandler* phandler,
  335. uint32_t id,
  336. MessageData* pdata) {
  337. // This should work even if it is used (unexpectedly).
  338. int64_t delay = static_cast<uint32_t>(TimeMillis()) - tstamp;
  339. return DoDelayPost(posted_from, delay, tstamp, phandler, id, pdata);
  340. }
  341. void MessageQueue::PostAt(const Location& posted_from,
  342. int64_t tstamp,
  343. MessageHandler* phandler,
  344. uint32_t id,
  345. MessageData* pdata) {
  346. return DoDelayPost(posted_from, TimeUntil(tstamp), tstamp, phandler, id,
  347. pdata);
  348. }
  349. void MessageQueue::DoDelayPost(const Location& posted_from,
  350. int64_t cmsDelay,
  351. int64_t tstamp,
  352. MessageHandler* phandler,
  353. uint32_t id,
  354. MessageData* pdata) {
  355. if (IsQuitting()) {
  356. delete pdata;
  357. return;
  358. }
  359. // Keep thread safe
  360. // Add to the priority queue. Gets sorted soonest first.
  361. // Signal for the multiplexer to return.
  362. {
  363. CritScope cs(&crit_);
  364. Message msg;
  365. msg.posted_from = posted_from;
  366. msg.phandler = phandler;
  367. msg.message_id = id;
  368. msg.pdata = pdata;
  369. DelayedMessage dmsg(cmsDelay, tstamp, dmsgq_next_num_, msg);
  370. dmsgq_.push(dmsg);
  371. // If this message queue processes 1 message every millisecond for 50 days,
  372. // we will wrap this number. Even then, only messages with identical times
  373. // will be misordered, and then only briefly. This is probably ok.
  374. ++dmsgq_next_num_;
  375. RTC_DCHECK_NE(0, dmsgq_next_num_);
  376. }
  377. WakeUpSocketServer();
  378. }
  379. int MessageQueue::GetDelay() {
  380. CritScope cs(&crit_);
  381. if (!msgq_.empty())
  382. return 0;
  383. if (!dmsgq_.empty()) {
  384. int delay = TimeUntil(dmsgq_.top().msTrigger_);
  385. if (delay < 0)
  386. delay = 0;
  387. return delay;
  388. }
  389. return kForever;
  390. }
  391. void MessageQueue::Clear(MessageHandler* phandler,
  392. uint32_t id,
  393. MessageList* removed) {
  394. CritScope cs(&crit_);
  395. ClearInternal(phandler, id, removed);
  396. }
  397. void MessageQueue::ClearInternal(MessageHandler* phandler,
  398. uint32_t id,
  399. MessageList* removed) {
  400. // Remove messages with phandler
  401. if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
  402. if (removed) {
  403. removed->push_back(msgPeek_);
  404. } else {
  405. delete msgPeek_.pdata;
  406. }
  407. fPeekKeep_ = false;
  408. }
  409. // Remove from ordered message queue
  410. for (MessageList::iterator it = msgq_.begin(); it != msgq_.end();) {
  411. if (it->Match(phandler, id)) {
  412. if (removed) {
  413. removed->push_back(*it);
  414. } else {
  415. delete it->pdata;
  416. }
  417. it = msgq_.erase(it);
  418. } else {
  419. ++it;
  420. }
  421. }
  422. // Remove from priority queue. Not directly iterable, so use this approach
  423. PriorityQueue::container_type::iterator new_end = dmsgq_.container().begin();
  424. for (PriorityQueue::container_type::iterator it = new_end;
  425. it != dmsgq_.container().end(); ++it) {
  426. if (it->msg_.Match(phandler, id)) {
  427. if (removed) {
  428. removed->push_back(it->msg_);
  429. } else {
  430. delete it->msg_.pdata;
  431. }
  432. } else {
  433. *new_end++ = *it;
  434. }
  435. }
  436. dmsgq_.container().erase(new_end, dmsgq_.container().end());
  437. dmsgq_.reheap();
  438. }
  439. void MessageQueue::Dispatch(Message* pmsg) {
  440. TRACE_EVENT2("webrtc", "MessageQueue::Dispatch", "src_file_and_line",
  441. pmsg->posted_from.file_and_line(), "src_func",
  442. pmsg->posted_from.function_name());
  443. int64_t start_time = TimeMillis();
  444. pmsg->phandler->OnMessage(pmsg);
  445. int64_t end_time = TimeMillis();
  446. int64_t diff = TimeDiff(end_time, start_time);
  447. if (diff >= kSlowDispatchLoggingThreshold) {
  448. RTC_LOG(LS_INFO) << "Message took " << diff
  449. << "ms to dispatch. Posted from: "
  450. << pmsg->posted_from.ToString();
  451. }
  452. }
  453. } // namespace rtc