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.

379 lines
10 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #ifdef POSIX
  28. #include <sys/time.h>
  29. #endif
  30. #include "talk/base/common.h"
  31. #include "talk/base/logging.h"
  32. #include "talk/base/messagequeue.h"
  33. #include "talk/base/physicalsocketserver.h"
  34. namespace talk_base {
  35. const uint32 kMaxMsgLatency = 150; // 150 ms
  36. //------------------------------------------------------------------
  37. // MessageQueueManager
  38. MessageQueueManager* MessageQueueManager::instance_;
  39. MessageQueueManager* MessageQueueManager::Instance() {
  40. // Note: This is not thread safe, but it is first called before threads are
  41. // spawned.
  42. if (!instance_)
  43. instance_ = new MessageQueueManager;
  44. return instance_;
  45. }
  46. MessageQueueManager::MessageQueueManager() {
  47. }
  48. MessageQueueManager::~MessageQueueManager() {
  49. }
  50. void MessageQueueManager::Add(MessageQueue *message_queue) {
  51. // MessageQueueManager methods should be non-reentrant, so we
  52. // ASSERT that is the case. If any of these ASSERT, please
  53. // contact bpm or jbeda.
  54. ASSERT(!crit_.CurrentThreadIsOwner());
  55. CritScope cs(&crit_);
  56. message_queues_.push_back(message_queue);
  57. }
  58. void MessageQueueManager::Remove(MessageQueue *message_queue) {
  59. ASSERT(!crit_.CurrentThreadIsOwner()); // See note above.
  60. // If this is the last MessageQueue, destroy the manager as well so that
  61. // we don't leak this object at program shutdown. As mentioned above, this is
  62. // not thread-safe, but this should only happen at program termination (when
  63. // the ThreadManager is destroyed, and threads are no longer active).
  64. bool destroy = false;
  65. {
  66. CritScope cs(&crit_);
  67. std::vector<MessageQueue *>::iterator iter;
  68. iter = std::find(message_queues_.begin(), message_queues_.end(),
  69. message_queue);
  70. if (iter != message_queues_.end()) {
  71. message_queues_.erase(iter);
  72. }
  73. destroy = message_queues_.empty();
  74. }
  75. if (destroy) {
  76. instance_ = NULL;
  77. delete this;
  78. }
  79. }
  80. void MessageQueueManager::Clear(MessageHandler *handler) {
  81. ASSERT(!crit_.CurrentThreadIsOwner()); // See note above.
  82. CritScope cs(&crit_);
  83. std::vector<MessageQueue *>::iterator iter;
  84. for (iter = message_queues_.begin(); iter != message_queues_.end(); iter++)
  85. (*iter)->Clear(handler);
  86. }
  87. //------------------------------------------------------------------
  88. // MessageQueue
  89. MessageQueue::MessageQueue(SocketServer* ss)
  90. : ss_(ss), fStop_(false), fPeekKeep_(false), active_(false),
  91. dmsgq_next_num_(0) {
  92. if (!ss_) {
  93. // Currently, MessageQueue holds a socket server, and is the base class for
  94. // Thread. It seems like it makes more sense for Thread to hold the socket
  95. // server, and provide it to the MessageQueue, since the Thread controls
  96. // the I/O model, and MQ is agnostic to those details. Anyway, this causes
  97. // messagequeue_unittest to depend on network libraries... yuck.
  98. default_ss_.reset(new PhysicalSocketServer());
  99. ss_ = default_ss_.get();
  100. }
  101. ss_->SetMessageQueue(this);
  102. }
  103. MessageQueue::~MessageQueue() {
  104. // The signal is done from here to ensure
  105. // that it always gets called when the queue
  106. // is going away.
  107. SignalQueueDestroyed();
  108. if (active_) {
  109. MessageQueueManager::Instance()->Remove(this);
  110. Clear(NULL);
  111. }
  112. if (ss_) {
  113. ss_->SetMessageQueue(NULL);
  114. }
  115. }
  116. void MessageQueue::set_socketserver(SocketServer* ss) {
  117. ss_ = ss ? ss : default_ss_.get();
  118. ss_->SetMessageQueue(this);
  119. }
  120. void MessageQueue::Quit() {
  121. fStop_ = true;
  122. ss_->WakeUp();
  123. }
  124. bool MessageQueue::IsQuitting() {
  125. return fStop_;
  126. }
  127. void MessageQueue::Restart() {
  128. fStop_ = false;
  129. }
  130. bool MessageQueue::Peek(Message *pmsg, int cmsWait) {
  131. if (fPeekKeep_) {
  132. *pmsg = msgPeek_;
  133. return true;
  134. }
  135. if (!Get(pmsg, cmsWait))
  136. return false;
  137. msgPeek_ = *pmsg;
  138. fPeekKeep_ = true;
  139. return true;
  140. }
  141. bool MessageQueue::Get(Message *pmsg, int cmsWait, bool process_io) {
  142. // Return and clear peek if present
  143. // Always return the peek if it exists so there is Peek/Get symmetry
  144. if (fPeekKeep_) {
  145. *pmsg = msgPeek_;
  146. fPeekKeep_ = false;
  147. return true;
  148. }
  149. // Get w/wait + timer scan / dispatch + socket / event multiplexer dispatch
  150. int cmsTotal = cmsWait;
  151. int cmsElapsed = 0;
  152. uint32 msStart = Time();
  153. uint32 msCurrent = msStart;
  154. while (true) {
  155. // Check for sent messages
  156. ReceiveSends();
  157. // Check queues
  158. int cmsDelayNext = kForever;
  159. {
  160. CritScope cs(&crit_);
  161. // Check for delayed messages that have been triggered
  162. // Calc the next trigger too
  163. while (!dmsgq_.empty()) {
  164. if (TimeIsLater(msCurrent, dmsgq_.top().msTrigger_)) {
  165. cmsDelayNext = TimeDiff(dmsgq_.top().msTrigger_, msCurrent);
  166. break;
  167. }
  168. msgq_.push_back(dmsgq_.top().msg_);
  169. dmsgq_.pop();
  170. }
  171. // Check for posted events
  172. while (!msgq_.empty()) {
  173. *pmsg = msgq_.front();
  174. if (pmsg->ts_sensitive) {
  175. long delay = TimeDiff(msCurrent, pmsg->ts_sensitive);
  176. if (delay > 0) {
  177. LOG_F(LS_WARNING) << "id: " << pmsg->message_id << " delay: "
  178. << (delay + kMaxMsgLatency) << "ms";
  179. }
  180. }
  181. msgq_.pop_front();
  182. if (MQID_DISPOSE == pmsg->message_id) {
  183. ASSERT(NULL == pmsg->phandler);
  184. delete pmsg->pdata;
  185. continue;
  186. }
  187. return true;
  188. }
  189. }
  190. if (fStop_)
  191. break;
  192. // Which is shorter, the delay wait or the asked wait?
  193. int cmsNext;
  194. if (cmsWait == kForever) {
  195. cmsNext = cmsDelayNext;
  196. } else {
  197. cmsNext = _max(0, cmsTotal - cmsElapsed);
  198. if ((cmsDelayNext != kForever) && (cmsDelayNext < cmsNext))
  199. cmsNext = cmsDelayNext;
  200. }
  201. // Wait and multiplex in the meantime
  202. if (!ss_->Wait(cmsNext, process_io))
  203. return false;
  204. // If the specified timeout expired, return
  205. msCurrent = Time();
  206. cmsElapsed = TimeDiff(msCurrent, msStart);
  207. if (cmsWait != kForever) {
  208. if (cmsElapsed >= cmsWait)
  209. return false;
  210. }
  211. }
  212. return false;
  213. }
  214. void MessageQueue::ReceiveSends() {
  215. }
  216. void MessageQueue::Post(MessageHandler *phandler, uint32 id,
  217. MessageData *pdata, bool time_sensitive) {
  218. if (fStop_)
  219. return;
  220. // Keep thread safe
  221. // Add the message to the end of the queue
  222. // Signal for the multiplexer to return
  223. CritScope cs(&crit_);
  224. EnsureActive();
  225. Message msg;
  226. msg.phandler = phandler;
  227. msg.message_id = id;
  228. msg.pdata = pdata;
  229. if (time_sensitive) {
  230. msg.ts_sensitive = Time() + kMaxMsgLatency;
  231. }
  232. msgq_.push_back(msg);
  233. ss_->WakeUp();
  234. }
  235. void MessageQueue::DoDelayPost(int cmsDelay, uint32 tstamp,
  236. MessageHandler *phandler, uint32 id, MessageData* pdata) {
  237. if (fStop_)
  238. return;
  239. // Keep thread safe
  240. // Add to the priority queue. Gets sorted soonest first.
  241. // Signal for the multiplexer to return.
  242. CritScope cs(&crit_);
  243. EnsureActive();
  244. Message msg;
  245. msg.phandler = phandler;
  246. msg.message_id = id;
  247. msg.pdata = pdata;
  248. DelayedMessage dmsg(cmsDelay, tstamp, dmsgq_next_num_, msg);
  249. dmsgq_.push(dmsg);
  250. // If this message queue processes 1 message every millisecond for 50 days,
  251. // we will wrap this number. Even then, only messages with identical times
  252. // will be misordered, and then only briefly. This is probably ok.
  253. VERIFY(0 != ++dmsgq_next_num_);
  254. ss_->WakeUp();
  255. }
  256. int MessageQueue::GetDelay() {
  257. CritScope cs(&crit_);
  258. if (!msgq_.empty())
  259. return 0;
  260. if (!dmsgq_.empty()) {
  261. int delay = TimeUntil(dmsgq_.top().msTrigger_);
  262. if (delay < 0)
  263. delay = 0;
  264. return delay;
  265. }
  266. return kForever;
  267. }
  268. void MessageQueue::Clear(MessageHandler *phandler, uint32 id,
  269. MessageList* removed) {
  270. CritScope cs(&crit_);
  271. // Remove messages with phandler
  272. if (fPeekKeep_ && msgPeek_.Match(phandler, id)) {
  273. if (removed) {
  274. removed->push_back(msgPeek_);
  275. } else {
  276. delete msgPeek_.pdata;
  277. }
  278. fPeekKeep_ = false;
  279. }
  280. // Remove from ordered message queue
  281. for (MessageList::iterator it = msgq_.begin(); it != msgq_.end();) {
  282. if (it->Match(phandler, id)) {
  283. if (removed) {
  284. removed->push_back(*it);
  285. } else {
  286. delete it->pdata;
  287. }
  288. it = msgq_.erase(it);
  289. } else {
  290. ++it;
  291. }
  292. }
  293. // Remove from priority queue. Not directly iterable, so use this approach
  294. PriorityQueue::container_type::iterator new_end = dmsgq_.container().begin();
  295. for (PriorityQueue::container_type::iterator it = new_end;
  296. it != dmsgq_.container().end(); ++it) {
  297. if (it->msg_.Match(phandler, id)) {
  298. if (removed) {
  299. removed->push_back(it->msg_);
  300. } else {
  301. delete it->msg_.pdata;
  302. }
  303. } else {
  304. *new_end++ = *it;
  305. }
  306. }
  307. dmsgq_.container().erase(new_end, dmsgq_.container().end());
  308. dmsgq_.reheap();
  309. }
  310. void MessageQueue::Dispatch(Message *pmsg) {
  311. pmsg->phandler->OnMessage(pmsg);
  312. }
  313. void MessageQueue::EnsureActive() {
  314. ASSERT(crit_.CurrentThreadIsOwner());
  315. if (!active_) {
  316. active_ = true;
  317. MessageQueueManager::Instance()->Add(this);
  318. }
  319. }
  320. } // namespace talk_base