henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [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 | |
Henrik Kjellander | c036276 | 2017-06-29 08:03:04 +0200 | [diff] [blame] | 11 | #ifndef WEBRTC_RTC_BASE_MESSAGEQUEUE_H_ |
| 12 | #define WEBRTC_RTC_BASE_MESSAGEQUEUE_H_ |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 13 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 14 | #include <string.h> |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 15 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 16 | #include <algorithm> |
| 17 | #include <list> |
| 18 | #include <memory> |
| 19 | #include <queue> |
| 20 | #include <utility> |
| 21 | #include <vector> |
| 22 | |
kjellander | e96c45b | 2017-06-30 10:45:21 -0700 | [diff] [blame] | 23 | #include "webrtc/rtc_base/basictypes.h" |
| 24 | #include "webrtc/rtc_base/constructormagic.h" |
| 25 | #include "webrtc/rtc_base/criticalsection.h" |
| 26 | #include "webrtc/rtc_base/location.h" |
| 27 | #include "webrtc/rtc_base/messagehandler.h" |
| 28 | #include "webrtc/rtc_base/scoped_ref_ptr.h" |
| 29 | #include "webrtc/rtc_base/sigslot.h" |
| 30 | #include "webrtc/rtc_base/socketserver.h" |
| 31 | #include "webrtc/rtc_base/thread_annotations.h" |
| 32 | #include "webrtc/rtc_base/timeutils.h" |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [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. |
| 71 | std::vector<MessageQueue*> message_queues_ GUARDED_BY(crit_); |
| 72 | |
jbauch | 5b36173 | 2017-07-06 23:51:37 -0700 | [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 07:52:50 +0200 | [diff] [blame] | 76 | CriticalSection crit_; |
jbauch | 5b36173 | 2017-07-06 23:51:37 -0700 | [diff] [blame^] | 77 | size_t processing_ GUARDED_BY(crit_); |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [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 | |
nisse | bc8feda | 2017-06-29 06:21:20 -0700 | [diff] [blame] | 152 | // TODO(nisse): Replace RunnableData and FunctorData by a subclass of Message |
| 153 | // owning a QueuedTask. |
| 154 | class RunnableData : public MessageData { |
| 155 | public: |
| 156 | virtual void Run() = 0; |
| 157 | }; |
| 158 | |
| 159 | template <class FunctorT> |
| 160 | class FunctorData : public RunnableData { |
| 161 | public: |
| 162 | explicit FunctorData(FunctorT functor) : functor_(std::move(functor)) {} |
| 163 | void Run() override { functor_(); } |
| 164 | |
| 165 | private: |
| 166 | FunctorT functor_; |
| 167 | }; |
| 168 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 169 | const uint32_t MQID_ANY = static_cast<uint32_t>(-1); |
| 170 | const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2); |
| 171 | |
| 172 | // No destructor |
| 173 | |
| 174 | struct Message { |
| 175 | Message() |
| 176 | : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {} |
| 177 | inline bool Match(MessageHandler* handler, uint32_t id) const { |
| 178 | return (handler == nullptr || handler == phandler) && |
| 179 | (id == MQID_ANY || id == message_id); |
| 180 | } |
| 181 | Location posted_from; |
| 182 | MessageHandler *phandler; |
| 183 | uint32_t message_id; |
| 184 | MessageData *pdata; |
| 185 | int64_t ts_sensitive; |
| 186 | }; |
| 187 | |
| 188 | typedef std::list<Message> MessageList; |
| 189 | |
| 190 | // DelayedMessage goes into a priority queue, sorted by trigger time. Messages |
| 191 | // with the same trigger time are processed in num_ (FIFO) order. |
| 192 | |
| 193 | class DelayedMessage { |
| 194 | public: |
| 195 | DelayedMessage(int64_t delay, |
| 196 | int64_t trigger, |
| 197 | uint32_t num, |
| 198 | const Message& msg) |
| 199 | : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {} |
| 200 | |
| 201 | bool operator< (const DelayedMessage& dmsg) const { |
| 202 | return (dmsg.msTrigger_ < msTrigger_) |
| 203 | || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_)); |
| 204 | } |
| 205 | |
| 206 | int64_t cmsDelay_; // for debugging |
| 207 | int64_t msTrigger_; |
| 208 | uint32_t num_; |
| 209 | Message msg_; |
| 210 | }; |
| 211 | |
| 212 | class MessageQueue { |
| 213 | public: |
| 214 | static const int kForever = -1; |
| 215 | |
| 216 | // Create a new MessageQueue and optionally assign it to the passed |
| 217 | // SocketServer. Subclasses that override Clear should pass false for |
| 218 | // init_queue and call DoInit() from their constructor to prevent races |
| 219 | // with the MessageQueueManager using the object while the vtable is still |
| 220 | // being created. |
| 221 | MessageQueue(SocketServer* ss, bool init_queue); |
| 222 | MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue); |
| 223 | |
| 224 | // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL |
| 225 | // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race |
| 226 | // between the destructor modifying the vtable, and the MessageQueueManager |
| 227 | // calling Clear on the object from a different thread. |
| 228 | virtual ~MessageQueue(); |
| 229 | |
| 230 | SocketServer* socketserver(); |
| 231 | |
| 232 | // Note: The behavior of MessageQueue has changed. When a MQ is stopped, |
| 233 | // futher Posts and Sends will fail. However, any pending Sends and *ready* |
| 234 | // Posts (as opposed to unexpired delayed Posts) will be delivered before |
| 235 | // Get (or Peek) returns false. By guaranteeing delivery of those messages, |
| 236 | // we eliminate the race condition when an MessageHandler and MessageQueue |
| 237 | // may be destroyed independently of each other. |
| 238 | virtual void Quit(); |
| 239 | virtual bool IsQuitting(); |
| 240 | virtual void Restart(); |
| 241 | // Not all message queues actually process messages (such as SignalThread). |
| 242 | // In those cases, it's important to know, before posting, that it won't be |
| 243 | // Processed. Normally, this would be true until IsQuitting() is true. |
| 244 | virtual bool IsProcessingMessages(); |
| 245 | |
| 246 | // Get() will process I/O until: |
| 247 | // 1) A message is available (returns true) |
| 248 | // 2) cmsWait seconds have elapsed (returns false) |
| 249 | // 3) Stop() is called (returns false) |
| 250 | virtual bool Get(Message *pmsg, int cmsWait = kForever, |
| 251 | bool process_io = true); |
| 252 | virtual bool Peek(Message *pmsg, int cmsWait = 0); |
| 253 | virtual void Post(const Location& posted_from, |
| 254 | MessageHandler* phandler, |
| 255 | uint32_t id = 0, |
| 256 | MessageData* pdata = nullptr, |
| 257 | bool time_sensitive = false); |
nisse | bc8feda | 2017-06-29 06:21:20 -0700 | [diff] [blame] | 258 | |
| 259 | // TODO(nisse): Replace with a method for posting a |
| 260 | // std::unique_ptr<QueuedTask>, to ease gradual conversion to using TaskQueue. |
| 261 | template <class FunctorT, |
| 262 | // Additional type check, or else it collides with calls to the |
| 263 | // above Post method with the optional arguments omitted. |
| 264 | typename std::enable_if<!std::is_pointer<FunctorT>::value>::type* = |
| 265 | nullptr> |
| 266 | void Post(const Location& posted_from, FunctorT functor) { |
| 267 | PostFunctorInternal(posted_from, |
| 268 | new FunctorData<FunctorT>(std::move(functor))); |
| 269 | } |
| 270 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 271 | virtual void PostDelayed(const Location& posted_from, |
| 272 | int cmsDelay, |
| 273 | MessageHandler* phandler, |
| 274 | uint32_t id = 0, |
| 275 | MessageData* pdata = nullptr); |
| 276 | virtual void PostAt(const Location& posted_from, |
| 277 | int64_t tstamp, |
| 278 | MessageHandler* phandler, |
| 279 | uint32_t id = 0, |
| 280 | MessageData* pdata = nullptr); |
| 281 | // TODO(honghaiz): Remove this when all the dependencies are removed. |
| 282 | virtual void PostAt(const Location& posted_from, |
| 283 | uint32_t tstamp, |
| 284 | MessageHandler* phandler, |
| 285 | uint32_t id = 0, |
| 286 | MessageData* pdata = nullptr); |
| 287 | virtual void Clear(MessageHandler* phandler, |
| 288 | uint32_t id = MQID_ANY, |
| 289 | MessageList* removed = nullptr); |
| 290 | virtual void Dispatch(Message *pmsg); |
| 291 | virtual void ReceiveSends(); |
| 292 | |
| 293 | // Amount of time until the next message can be retrieved |
| 294 | virtual int GetDelay(); |
| 295 | |
| 296 | bool empty() const { return size() == 0u; } |
| 297 | size_t size() const { |
| 298 | CritScope cs(&crit_); // msgq_.size() is not thread safe. |
| 299 | return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u); |
| 300 | } |
| 301 | |
| 302 | // Internally posts a message which causes the doomed object to be deleted |
| 303 | template<class T> void Dispose(T* doomed) { |
| 304 | if (doomed) { |
| 305 | Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed)); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // When this signal is sent out, any references to this queue should |
| 310 | // no longer be used. |
| 311 | sigslot::signal0<> SignalQueueDestroyed; |
| 312 | |
| 313 | protected: |
| 314 | class PriorityQueue : public std::priority_queue<DelayedMessage> { |
| 315 | public: |
| 316 | container_type& container() { return c; } |
| 317 | void reheap() { make_heap(c.begin(), c.end(), comp); } |
| 318 | }; |
| 319 | |
| 320 | void DoDelayPost(const Location& posted_from, |
| 321 | int64_t cmsDelay, |
| 322 | int64_t tstamp, |
| 323 | MessageHandler* phandler, |
| 324 | uint32_t id, |
| 325 | MessageData* pdata); |
| 326 | |
| 327 | // Perform initialization, subclasses must call this from their constructor |
| 328 | // if false was passed as init_queue to the MessageQueue constructor. |
| 329 | void DoInit(); |
| 330 | |
| 331 | // Perform cleanup, subclasses that override Clear must call this from the |
| 332 | // destructor. |
| 333 | void DoDestroy(); |
| 334 | |
| 335 | void WakeUpSocketServer(); |
| 336 | |
| 337 | bool fPeekKeep_; |
| 338 | Message msgPeek_; |
| 339 | MessageList msgq_ GUARDED_BY(crit_); |
| 340 | PriorityQueue dmsgq_ GUARDED_BY(crit_); |
| 341 | uint32_t dmsgq_next_num_ GUARDED_BY(crit_); |
| 342 | CriticalSection crit_; |
| 343 | bool fInitialized_; |
| 344 | bool fDestroyed_; |
| 345 | |
| 346 | private: |
nisse | bc8feda | 2017-06-29 06:21:20 -0700 | [diff] [blame] | 347 | void PostFunctorInternal(const Location& posted_from, |
| 348 | RunnableData* message_data); |
| 349 | |
Henrik Kjellander | ec78f1c | 2017-06-29 07:52:50 +0200 | [diff] [blame] | 350 | volatile int stop_; |
| 351 | |
| 352 | // The SocketServer might not be owned by MessageQueue. |
| 353 | SocketServer* const ss_; |
| 354 | // Used if SocketServer ownership lies with |this|. |
| 355 | std::unique_ptr<SocketServer> own_ss_; |
| 356 | |
| 357 | RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue); |
| 358 | }; |
| 359 | |
| 360 | } // namespace rtc |
henrike@webrtc.org | f048872 | 2014-05-13 18:00:26 +0000 | [diff] [blame] | 361 | |
Henrik Kjellander | c036276 | 2017-06-29 08:03:04 +0200 | [diff] [blame] | 362 | #endif // WEBRTC_RTC_BASE_MESSAGEQUEUE_H_ |