blob: e7e479285d20c8339a62ee63eaf3aa50d099e02e [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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 Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_MESSAGEQUEUE_H_
12#define RTC_BASE_MESSAGEQUEUE_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <string.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <algorithm>
17#include <list>
18#include <memory>
19#include <queue>
20#include <utility>
21#include <vector>
22
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/constructormagic.h"
24#include "rtc_base/criticalsection.h"
25#include "rtc_base/location.h"
26#include "rtc_base/messagehandler.h"
27#include "rtc_base/scoped_ref_ptr.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/socketserver.h"
Artem Titove41c4332018-07-25 15:04:28 +020029#include "rtc_base/third_party/sigslot/sigslot.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/thread_annotations.h"
31#include "rtc_base/timeutils.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020032
33namespace rtc {
34
35struct Message;
36class MessageQueue;
37
38// MessageQueueManager does cleanup of of message queues
39
40class MessageQueueManager {
41 public:
Yves Gerey665174f2018-06-19 15:03:05 +020042 static void Add(MessageQueue* message_queue);
43 static void Remove(MessageQueue* message_queue);
44 static void Clear(MessageHandler* handler);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020045
Niels Möller8909a632018-09-06 08:42:44 +020046 // TODO(nisse): Delete alias, as soon as downstream code is updated.
47 static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); }
48
49 // For testing purposes, for use with a simulated clock.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020050 // Ensures that all message queues have processed delayed messages
51 // up until the current point in time.
Niels Möller8909a632018-09-06 08:42:44 +020052 static void ProcessAllMessageQueuesForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020053
54 private:
55 static MessageQueueManager* Instance();
56
57 MessageQueueManager();
58 ~MessageQueueManager();
59
Yves Gerey665174f2018-06-19 15:03:05 +020060 void AddInternal(MessageQueue* message_queue);
61 void RemoveInternal(MessageQueue* message_queue);
62 void ClearInternal(MessageHandler* handler);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020063 void ProcessAllMessageQueuesInternal();
64
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020065 // This list contains all live MessageQueues.
danilchap3c6abd22017-09-06 05:46:29 -070066 std::vector<MessageQueue*> message_queues_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020067
jbauch5b361732017-07-06 23:51:37 -070068 // Methods that don't modify the list of message queues may be called in a
69 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
70 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -070072 size_t processing_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020073};
74
75// Derive from this for specialized data
76// App manages lifetime, except when messages are purged
77
78class MessageData {
79 public:
80 MessageData() {}
81 virtual ~MessageData() {}
82};
83
84template <class T>
85class TypedMessageData : public MessageData {
86 public:
Yves Gerey665174f2018-06-19 15:03:05 +020087 explicit TypedMessageData(const T& data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020088 const T& data() const { return data_; }
89 T& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +020090
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091 private:
92 T data_;
93};
94
95// Like TypedMessageData, but for pointers that require a delete.
96template <class T>
97class ScopedMessageData : public MessageData {
98 public:
99 explicit ScopedMessageData(std::unique_ptr<T> data)
100 : data_(std::move(data)) {}
101 // Deprecated.
102 // TODO(deadbeef): Remove this once downstream applications stop using it.
103 explicit ScopedMessageData(T* data) : data_(data) {}
104 // Deprecated.
105 // TODO(deadbeef): Returning a reference to a unique ptr? Why. Get rid of
106 // this once downstream applications stop using it, then rename inner_data to
107 // just data.
108 const std::unique_ptr<T>& data() const { return data_; }
109 std::unique_ptr<T>& data() { return data_; }
110
111 const T& inner_data() const { return *data_; }
112 T& inner_data() { return *data_; }
113
114 private:
115 std::unique_ptr<T> data_;
116};
117
118// Like ScopedMessageData, but for reference counted pointers.
119template <class T>
120class ScopedRefMessageData : public MessageData {
121 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200122 explicit ScopedRefMessageData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123 const scoped_refptr<T>& data() const { return data_; }
124 scoped_refptr<T>& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200125
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200126 private:
127 scoped_refptr<T> data_;
128};
129
Yves Gerey665174f2018-06-19 15:03:05 +0200130template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200131inline MessageData* WrapMessageData(const T& data) {
132 return new TypedMessageData<T>(data);
133}
134
Yves Gerey665174f2018-06-19 15:03:05 +0200135template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200136inline const T& UseMessageData(MessageData* data) {
Yves Gerey665174f2018-06-19 15:03:05 +0200137 return static_cast<TypedMessageData<T>*>(data)->data();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200138}
139
Yves Gerey665174f2018-06-19 15:03:05 +0200140template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200141class DisposeData : public MessageData {
142 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200143 explicit DisposeData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200144 virtual ~DisposeData() { delete data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200145
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200146 private:
147 T* data_;
148};
149
150const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
151const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
152
153// No destructor
154
155struct Message {
156 Message()
157 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
158 inline bool Match(MessageHandler* handler, uint32_t id) const {
159 return (handler == nullptr || handler == phandler) &&
160 (id == MQID_ANY || id == message_id);
161 }
162 Location posted_from;
Yves Gerey665174f2018-06-19 15:03:05 +0200163 MessageHandler* phandler;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164 uint32_t message_id;
Yves Gerey665174f2018-06-19 15:03:05 +0200165 MessageData* pdata;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200166 int64_t ts_sensitive;
167};
168
169typedef std::list<Message> MessageList;
170
171// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
172// with the same trigger time are processed in num_ (FIFO) order.
173
174class DelayedMessage {
175 public:
176 DelayedMessage(int64_t delay,
177 int64_t trigger,
178 uint32_t num,
179 const Message& msg)
180 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
181
Yves Gerey665174f2018-06-19 15:03:05 +0200182 bool operator<(const DelayedMessage& dmsg) const {
183 return (dmsg.msTrigger_ < msTrigger_) ||
184 ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185 }
186
187 int64_t cmsDelay_; // for debugging
188 int64_t msTrigger_;
189 uint32_t num_;
190 Message msg_;
191};
192
193class MessageQueue {
194 public:
195 static const int kForever = -1;
196
197 // Create a new MessageQueue and optionally assign it to the passed
198 // SocketServer. Subclasses that override Clear should pass false for
199 // init_queue and call DoInit() from their constructor to prevent races
200 // with the MessageQueueManager using the object while the vtable is still
201 // being created.
202 MessageQueue(SocketServer* ss, bool init_queue);
203 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
204
205 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
206 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
207 // between the destructor modifying the vtable, and the MessageQueueManager
208 // calling Clear on the object from a different thread.
209 virtual ~MessageQueue();
210
211 SocketServer* socketserver();
212
213 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
214 // futher Posts and Sends will fail. However, any pending Sends and *ready*
215 // Posts (as opposed to unexpired delayed Posts) will be delivered before
216 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
217 // we eliminate the race condition when an MessageHandler and MessageQueue
218 // may be destroyed independently of each other.
219 virtual void Quit();
220 virtual bool IsQuitting();
221 virtual void Restart();
222 // Not all message queues actually process messages (such as SignalThread).
223 // In those cases, it's important to know, before posting, that it won't be
224 // Processed. Normally, this would be true until IsQuitting() is true.
Niels Möller8909a632018-09-06 08:42:44 +0200225 virtual bool IsProcessingMessagesForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200226
227 // Get() will process I/O until:
228 // 1) A message is available (returns true)
229 // 2) cmsWait seconds have elapsed (returns false)
230 // 3) Stop() is called (returns false)
Yves Gerey665174f2018-06-19 15:03:05 +0200231 virtual bool Get(Message* pmsg,
232 int cmsWait = kForever,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200233 bool process_io = true);
Yves Gerey665174f2018-06-19 15:03:05 +0200234 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235 virtual void Post(const Location& posted_from,
236 MessageHandler* phandler,
237 uint32_t id = 0,
238 MessageData* pdata = nullptr,
239 bool time_sensitive = false);
240 virtual void PostDelayed(const Location& posted_from,
241 int cmsDelay,
242 MessageHandler* phandler,
243 uint32_t id = 0,
244 MessageData* pdata = nullptr);
245 virtual void PostAt(const Location& posted_from,
246 int64_t tstamp,
247 MessageHandler* phandler,
248 uint32_t id = 0,
249 MessageData* pdata = nullptr);
250 // TODO(honghaiz): Remove this when all the dependencies are removed.
251 virtual void PostAt(const Location& posted_from,
252 uint32_t tstamp,
253 MessageHandler* phandler,
254 uint32_t id = 0,
255 MessageData* pdata = nullptr);
256 virtual void Clear(MessageHandler* phandler,
257 uint32_t id = MQID_ANY,
258 MessageList* removed = nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200259 virtual void Dispatch(Message* pmsg);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200260 virtual void ReceiveSends();
261
262 // Amount of time until the next message can be retrieved
263 virtual int GetDelay();
264
265 bool empty() const { return size() == 0u; }
266 size_t size() const {
267 CritScope cs(&crit_); // msgq_.size() is not thread safe.
268 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
269 }
270
271 // Internally posts a message which causes the doomed object to be deleted
Yves Gerey665174f2018-06-19 15:03:05 +0200272 template <class T>
273 void Dispose(T* doomed) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200274 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
Niels Möller5e007b72018-09-07 12:35:44 +0200301 // Does not take any lock. Must be called either while holding crit_, or by
302 // the destructor (by definition, the latter has exclusive access).
303 void ClearInternal(MessageHandler* phandler,
304 uint32_t id,
305 MessageList* removed) RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
306
307 // Perform cleanup; subclasses must call this from the destructor,
308 // and are not expected to actually hold the lock.
309 void DoDestroy() RTC_EXCLUSIVE_LOCKS_REQUIRED(&crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200310
311 void WakeUpSocketServer();
312
313 bool fPeekKeep_;
314 Message msgPeek_;
danilchap3c6abd22017-09-06 05:46:29 -0700315 MessageList msgq_ RTC_GUARDED_BY(crit_);
316 PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
317 uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200318 CriticalSection crit_;
319 bool fInitialized_;
320 bool fDestroyed_;
321
322 private:
323 volatile int stop_;
324
325 // The SocketServer might not be owned by MessageQueue.
326 SocketServer* const ss_;
327 // Used if SocketServer ownership lies with |this|.
328 std::unique_ptr<SocketServer> own_ss_;
329
330 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
331};
332
333} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200335#endif // RTC_BASE_MESSAGEQUEUE_H_