henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 | [diff] [blame] | 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 | |
Mirko Bonadei | 92ea95e | 2017-09-15 04:47:31 | [diff] [blame] | 11 | #ifndef RTC_BASE_MESSAGEQUEUE_H_ |
| 12 | #define RTC_BASE_MESSAGEQUEUE_H_ |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 | [diff] [blame] | 13 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 14 | #include <string.h> |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 | [diff] [blame] | 15 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 16 | #include <algorithm> |
| 17 | #include <list> |
| 18 | #include <memory> |
| 19 | #include <queue> |
| 20 | #include <utility> |
| 21 | #include <vector> |
| 22 | |
Mirko Bonadei | 92ea95e | 2017-09-15 04:47:31 | [diff] [blame] | 23 | #include "rtc_base/basictypes.h" |
| 24 | #include "rtc_base/constructormagic.h" |
| 25 | #include "rtc_base/criticalsection.h" |
| 26 | #include "rtc_base/location.h" |
| 27 | #include "rtc_base/messagehandler.h" |
| 28 | #include "rtc_base/scoped_ref_ptr.h" |
| 29 | #include "rtc_base/sigslot.h" |
| 30 | #include "rtc_base/socketserver.h" |
| 31 | #include "rtc_base/thread_annotations.h" |
| 32 | #include "rtc_base/timeutils.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 33 | |
| 34 | namespace rtc { |
| 35 | |
| 36 | struct Message; |
| 37 | class MessageQueue; |
| 38 | |
| 39 | // MessageQueueManager does cleanup of of message queues |
| 40 | |
| 41 | class MessageQueueManager { |
| 42 | public: |
| 43 | static void Add(MessageQueue *message_queue); |
| 44 | static void Remove(MessageQueue *message_queue); |
| 45 | static void Clear(MessageHandler *handler); |
| 46 | |
| 47 | // For testing purposes, we expose whether or not the MessageQueueManager |
| 48 | // instance has been initialized. It has no other use relative to the rest of |
| 49 | // the functions of this class, which auto-initialize the underlying |
| 50 | // MessageQueueManager instance when necessary. |
| 51 | static bool IsInitialized(); |
| 52 | |
| 53 | // Mainly for testing purposes, for use with a simulated clock. |
| 54 | // Ensures that all message queues have processed delayed messages |
| 55 | // up until the current point in time. |
| 56 | static void ProcessAllMessageQueues(); |
| 57 | |
| 58 | private: |
| 59 | static MessageQueueManager* Instance(); |
| 60 | |
| 61 | MessageQueueManager(); |
| 62 | ~MessageQueueManager(); |
| 63 | |
| 64 | void AddInternal(MessageQueue *message_queue); |
| 65 | void RemoveInternal(MessageQueue *message_queue); |
| 66 | void ClearInternal(MessageHandler *handler); |
| 67 | void ProcessAllMessageQueuesInternal(); |
| 68 | |
| 69 | static MessageQueueManager* instance_; |
| 70 | // This list contains all live MessageQueues. |
danilchap | 3c6abd2 | 2017-09-06 12:46:29 | [diff] [blame] | 71 | std::vector<MessageQueue*> message_queues_ RTC_GUARDED_BY(crit_); |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 72 | |
jbauch | 5b36173 | 2017-07-07 06:51:37 | [diff] [blame] | 73 | // Methods that don't modify the list of message queues may be called in a |
| 74 | // re-entrant fashion. "processing_" keeps track of the depth of re-entrant |
| 75 | // calls. |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 76 | CriticalSection crit_; |
danilchap | 3c6abd2 | 2017-09-06 12:46:29 | [diff] [blame] | 77 | size_t processing_ RTC_GUARDED_BY(crit_); |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 78 | }; |
| 79 | |
| 80 | // Derive from this for specialized data |
| 81 | // App manages lifetime, except when messages are purged |
| 82 | |
| 83 | class MessageData { |
| 84 | public: |
| 85 | MessageData() {} |
| 86 | virtual ~MessageData() {} |
| 87 | }; |
| 88 | |
| 89 | template <class T> |
| 90 | class TypedMessageData : public MessageData { |
| 91 | public: |
| 92 | explicit TypedMessageData(const T& data) : data_(data) { } |
| 93 | const T& data() const { return data_; } |
| 94 | T& data() { return data_; } |
| 95 | private: |
| 96 | T data_; |
| 97 | }; |
| 98 | |
| 99 | // Like TypedMessageData, but for pointers that require a delete. |
| 100 | template <class T> |
| 101 | class ScopedMessageData : public MessageData { |
| 102 | public: |
| 103 | explicit ScopedMessageData(std::unique_ptr<T> data) |
| 104 | : data_(std::move(data)) {} |
| 105 | // Deprecated. |
| 106 | // TODO(deadbeef): Remove this once downstream applications stop using it. |
| 107 | explicit ScopedMessageData(T* data) : data_(data) {} |
| 108 | // Deprecated. |
| 109 | // TODO(deadbeef): Returning a reference to a unique ptr? Why. Get rid of |
| 110 | // this once downstream applications stop using it, then rename inner_data to |
| 111 | // just data. |
| 112 | const std::unique_ptr<T>& data() const { return data_; } |
| 113 | std::unique_ptr<T>& data() { return data_; } |
| 114 | |
| 115 | const T& inner_data() const { return *data_; } |
| 116 | T& inner_data() { return *data_; } |
| 117 | |
| 118 | private: |
| 119 | std::unique_ptr<T> data_; |
| 120 | }; |
| 121 | |
| 122 | // Like ScopedMessageData, but for reference counted pointers. |
| 123 | template <class T> |
| 124 | class ScopedRefMessageData : public MessageData { |
| 125 | public: |
| 126 | explicit ScopedRefMessageData(T* data) : data_(data) { } |
| 127 | const scoped_refptr<T>& data() const { return data_; } |
| 128 | scoped_refptr<T>& data() { return data_; } |
| 129 | private: |
| 130 | scoped_refptr<T> data_; |
| 131 | }; |
| 132 | |
| 133 | template<class T> |
| 134 | inline MessageData* WrapMessageData(const T& data) { |
| 135 | return new TypedMessageData<T>(data); |
| 136 | } |
| 137 | |
| 138 | template<class T> |
| 139 | inline const T& UseMessageData(MessageData* data) { |
| 140 | return static_cast< TypedMessageData<T>* >(data)->data(); |
| 141 | } |
| 142 | |
| 143 | template<class T> |
| 144 | class DisposeData : public MessageData { |
| 145 | public: |
| 146 | explicit DisposeData(T* data) : data_(data) { } |
| 147 | virtual ~DisposeData() { delete data_; } |
| 148 | private: |
| 149 | T* data_; |
| 150 | }; |
| 151 | |
| 152 | const uint32_t MQID_ANY = static_cast<uint32_t>(-1); |
| 153 | const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2); |
| 154 | |
| 155 | // No destructor |
| 156 | |
| 157 | struct Message { |
| 158 | Message() |
| 159 | : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {} |
| 160 | inline bool Match(MessageHandler* handler, uint32_t id) const { |
| 161 | return (handler == nullptr || handler == phandler) && |
| 162 | (id == MQID_ANY || id == message_id); |
| 163 | } |
| 164 | Location posted_from; |
| 165 | MessageHandler *phandler; |
| 166 | uint32_t message_id; |
| 167 | MessageData *pdata; |
| 168 | int64_t ts_sensitive; |
| 169 | }; |
| 170 | |
| 171 | typedef std::list<Message> MessageList; |
| 172 | |
| 173 | // DelayedMessage goes into a priority queue, sorted by trigger time. Messages |
| 174 | // with the same trigger time are processed in num_ (FIFO) order. |
| 175 | |
| 176 | class DelayedMessage { |
| 177 | public: |
| 178 | DelayedMessage(int64_t delay, |
| 179 | int64_t trigger, |
| 180 | uint32_t num, |
| 181 | const Message& msg) |
| 182 | : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {} |
| 183 | |
| 184 | bool operator< (const DelayedMessage& dmsg) const { |
| 185 | return (dmsg.msTrigger_ < msTrigger_) |
| 186 | || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_)); |
| 187 | } |
| 188 | |
| 189 | int64_t cmsDelay_; // for debugging |
| 190 | int64_t msTrigger_; |
| 191 | uint32_t num_; |
| 192 | Message msg_; |
| 193 | }; |
| 194 | |
| 195 | class MessageQueue { |
| 196 | public: |
| 197 | static const int kForever = -1; |
| 198 | |
| 199 | // Create a new MessageQueue and optionally assign it to the passed |
| 200 | // SocketServer. Subclasses that override Clear should pass false for |
| 201 | // init_queue and call DoInit() from their constructor to prevent races |
| 202 | // with the MessageQueueManager using the object while the vtable is still |
| 203 | // being created. |
| 204 | MessageQueue(SocketServer* ss, bool init_queue); |
| 205 | MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue); |
| 206 | |
| 207 | // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL |
| 208 | // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race |
| 209 | // between the destructor modifying the vtable, and the MessageQueueManager |
| 210 | // calling Clear on the object from a different thread. |
| 211 | virtual ~MessageQueue(); |
| 212 | |
| 213 | SocketServer* socketserver(); |
| 214 | |
| 215 | // Note: The behavior of MessageQueue has changed. When a MQ is stopped, |
| 216 | // futher Posts and Sends will fail. However, any pending Sends and *ready* |
| 217 | // Posts (as opposed to unexpired delayed Posts) will be delivered before |
| 218 | // Get (or Peek) returns false. By guaranteeing delivery of those messages, |
| 219 | // we eliminate the race condition when an MessageHandler and MessageQueue |
| 220 | // may be destroyed independently of each other. |
| 221 | virtual void Quit(); |
| 222 | virtual bool IsQuitting(); |
| 223 | virtual void Restart(); |
| 224 | // Not all message queues actually process messages (such as SignalThread). |
| 225 | // In those cases, it's important to know, before posting, that it won't be |
| 226 | // Processed. Normally, this would be true until IsQuitting() is true. |
| 227 | virtual bool IsProcessingMessages(); |
| 228 | |
| 229 | // Get() will process I/O until: |
| 230 | // 1) A message is available (returns true) |
| 231 | // 2) cmsWait seconds have elapsed (returns false) |
| 232 | // 3) Stop() is called (returns false) |
| 233 | virtual bool Get(Message *pmsg, int cmsWait = kForever, |
| 234 | bool process_io = true); |
| 235 | virtual bool Peek(Message *pmsg, int cmsWait = 0); |
| 236 | virtual void Post(const Location& posted_from, |
| 237 | MessageHandler* phandler, |
| 238 | uint32_t id = 0, |
| 239 | MessageData* pdata = nullptr, |
| 240 | bool time_sensitive = false); |
| 241 | virtual void PostDelayed(const Location& posted_from, |
| 242 | int cmsDelay, |
| 243 | MessageHandler* phandler, |
| 244 | uint32_t id = 0, |
| 245 | MessageData* pdata = nullptr); |
| 246 | virtual void PostAt(const Location& posted_from, |
| 247 | int64_t tstamp, |
| 248 | MessageHandler* phandler, |
| 249 | uint32_t id = 0, |
| 250 | MessageData* pdata = nullptr); |
| 251 | // TODO(honghaiz): Remove this when all the dependencies are removed. |
| 252 | virtual void PostAt(const Location& posted_from, |
| 253 | uint32_t tstamp, |
| 254 | MessageHandler* phandler, |
| 255 | uint32_t id = 0, |
| 256 | MessageData* pdata = nullptr); |
| 257 | virtual void Clear(MessageHandler* phandler, |
| 258 | uint32_t id = MQID_ANY, |
| 259 | MessageList* removed = nullptr); |
| 260 | virtual void Dispatch(Message *pmsg); |
| 261 | virtual void ReceiveSends(); |
| 262 | |
| 263 | // Amount of time until the next message can be retrieved |
| 264 | virtual int GetDelay(); |
| 265 | |
| 266 | bool empty() const { return size() == 0u; } |
| 267 | size_t size() const { |
| 268 | CritScope cs(&crit_); // msgq_.size() is not thread safe. |
| 269 | return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u); |
| 270 | } |
| 271 | |
| 272 | // Internally posts a message which causes the doomed object to be deleted |
| 273 | template<class T> void Dispose(T* doomed) { |
| 274 | if (doomed) { |
| 275 | Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed)); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // When this signal is sent out, any references to this queue should |
| 280 | // no longer be used. |
| 281 | sigslot::signal0<> SignalQueueDestroyed; |
| 282 | |
| 283 | protected: |
| 284 | class PriorityQueue : public std::priority_queue<DelayedMessage> { |
| 285 | public: |
| 286 | container_type& container() { return c; } |
| 287 | void reheap() { make_heap(c.begin(), c.end(), comp); } |
| 288 | }; |
| 289 | |
| 290 | void DoDelayPost(const Location& posted_from, |
| 291 | int64_t cmsDelay, |
| 292 | int64_t tstamp, |
| 293 | MessageHandler* phandler, |
| 294 | uint32_t id, |
| 295 | MessageData* pdata); |
| 296 | |
| 297 | // Perform initialization, subclasses must call this from their constructor |
| 298 | // if false was passed as init_queue to the MessageQueue constructor. |
| 299 | void DoInit(); |
| 300 | |
| 301 | // Perform cleanup, subclasses that override Clear must call this from the |
| 302 | // destructor. |
| 303 | void DoDestroy(); |
| 304 | |
| 305 | void WakeUpSocketServer(); |
| 306 | |
| 307 | bool fPeekKeep_; |
| 308 | Message msgPeek_; |
danilchap | 3c6abd2 | 2017-09-06 12:46:29 | [diff] [blame] | 309 | MessageList msgq_ RTC_GUARDED_BY(crit_); |
| 310 | PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_); |
| 311 | uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_); |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 312 | CriticalSection crit_; |
| 313 | bool fInitialized_; |
| 314 | bool fDestroyed_; |
| 315 | |
| 316 | private: |
| 317 | volatile int stop_; |
| 318 | |
| 319 | // The SocketServer might not be owned by MessageQueue. |
| 320 | SocketServer* const ss_; |
| 321 | // Used if SocketServer ownership lies with |this|. |
| 322 | std::unique_ptr<SocketServer> own_ss_; |
| 323 | |
| 324 | RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue); |
| 325 | }; |
| 326 | |
| 327 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 | [diff] [blame] | 328 | |
Mirko Bonadei | 92ea95e | 2017-09-15 04:47:31 | [diff] [blame] | 329 | #endif // RTC_BASE_MESSAGEQUEUE_H_ |