blob: fe64c9c4326d79a7152dd1488f7bb0eaf75e66ae [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
46 // For testing purposes, we expose whether or not the MessageQueueManager
47 // instance has been initialized. It has no other use relative to the rest of
48 // the functions of this class, which auto-initialize the underlying
49 // MessageQueueManager instance when necessary.
50 static bool IsInitialized();
51
52 // Mainly for testing purposes, for use with a simulated clock.
53 // Ensures that all message queues have processed delayed messages
54 // up until the current point in time.
55 static void ProcessAllMessageQueues();
56
57 private:
58 static MessageQueueManager* Instance();
59
60 MessageQueueManager();
61 ~MessageQueueManager();
62
Yves Gerey665174f2018-06-19 15:03:05 +020063 void AddInternal(MessageQueue* message_queue);
64 void RemoveInternal(MessageQueue* message_queue);
65 void ClearInternal(MessageHandler* handler);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020066 void ProcessAllMessageQueuesInternal();
67
68 static MessageQueueManager* instance_;
69 // This list contains all live MessageQueues.
danilchap3c6abd22017-09-06 05:46:29 -070070 std::vector<MessageQueue*> message_queues_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071
jbauch5b361732017-07-06 23:51:37 -070072 // Methods that don't modify the list of message queues may be called in a
73 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
74 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020075 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -070076 size_t processing_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020077};
78
79// Derive from this for specialized data
80// App manages lifetime, except when messages are purged
81
82class MessageData {
83 public:
84 MessageData() {}
85 virtual ~MessageData() {}
86};
87
88template <class T>
89class TypedMessageData : public MessageData {
90 public:
Yves Gerey665174f2018-06-19 15:03:05 +020091 explicit TypedMessageData(const T& data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020092 const T& data() const { return data_; }
93 T& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +020094
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020095 private:
96 T data_;
97};
98
99// Like TypedMessageData, but for pointers that require a delete.
100template <class T>
101class 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.
123template <class T>
124class ScopedRefMessageData : public MessageData {
125 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200126 explicit ScopedRefMessageData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127 const scoped_refptr<T>& data() const { return data_; }
128 scoped_refptr<T>& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200129
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200130 private:
131 scoped_refptr<T> data_;
132};
133
Yves Gerey665174f2018-06-19 15:03:05 +0200134template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200135inline MessageData* WrapMessageData(const T& data) {
136 return new TypedMessageData<T>(data);
137}
138
Yves Gerey665174f2018-06-19 15:03:05 +0200139template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140inline const T& UseMessageData(MessageData* data) {
Yves Gerey665174f2018-06-19 15:03:05 +0200141 return static_cast<TypedMessageData<T>*>(data)->data();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200142}
143
Yves Gerey665174f2018-06-19 15:03:05 +0200144template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145class DisposeData : public MessageData {
146 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200147 explicit DisposeData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148 virtual ~DisposeData() { delete data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200149
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200150 private:
151 T* data_;
152};
153
154const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
155const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
156
157// No destructor
158
159struct Message {
160 Message()
161 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
162 inline bool Match(MessageHandler* handler, uint32_t id) const {
163 return (handler == nullptr || handler == phandler) &&
164 (id == MQID_ANY || id == message_id);
165 }
166 Location posted_from;
Yves Gerey665174f2018-06-19 15:03:05 +0200167 MessageHandler* phandler;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200168 uint32_t message_id;
Yves Gerey665174f2018-06-19 15:03:05 +0200169 MessageData* pdata;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200170 int64_t ts_sensitive;
171};
172
173typedef std::list<Message> MessageList;
174
175// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
176// with the same trigger time are processed in num_ (FIFO) order.
177
178class DelayedMessage {
179 public:
180 DelayedMessage(int64_t delay,
181 int64_t trigger,
182 uint32_t num,
183 const Message& msg)
184 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
185
Yves Gerey665174f2018-06-19 15:03:05 +0200186 bool operator<(const DelayedMessage& dmsg) const {
187 return (dmsg.msTrigger_ < msTrigger_) ||
188 ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200189 }
190
191 int64_t cmsDelay_; // for debugging
192 int64_t msTrigger_;
193 uint32_t num_;
194 Message msg_;
195};
196
197class MessageQueue {
198 public:
199 static const int kForever = -1;
200
201 // Create a new MessageQueue and optionally assign it to the passed
202 // SocketServer. Subclasses that override Clear should pass false for
203 // init_queue and call DoInit() from their constructor to prevent races
204 // with the MessageQueueManager using the object while the vtable is still
205 // being created.
206 MessageQueue(SocketServer* ss, bool init_queue);
207 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
208
209 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
210 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
211 // between the destructor modifying the vtable, and the MessageQueueManager
212 // calling Clear on the object from a different thread.
213 virtual ~MessageQueue();
214
215 SocketServer* socketserver();
216
217 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
218 // futher Posts and Sends will fail. However, any pending Sends and *ready*
219 // Posts (as opposed to unexpired delayed Posts) will be delivered before
220 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
221 // we eliminate the race condition when an MessageHandler and MessageQueue
222 // may be destroyed independently of each other.
223 virtual void Quit();
224 virtual bool IsQuitting();
225 virtual void Restart();
226 // Not all message queues actually process messages (such as SignalThread).
227 // In those cases, it's important to know, before posting, that it won't be
228 // Processed. Normally, this would be true until IsQuitting() is true.
229 virtual bool IsProcessingMessages();
230
231 // Get() will process I/O until:
232 // 1) A message is available (returns true)
233 // 2) cmsWait seconds have elapsed (returns false)
234 // 3) Stop() is called (returns false)
Yves Gerey665174f2018-06-19 15:03:05 +0200235 virtual bool Get(Message* pmsg,
236 int cmsWait = kForever,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200237 bool process_io = true);
Yves Gerey665174f2018-06-19 15:03:05 +0200238 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200239 virtual void Post(const Location& posted_from,
240 MessageHandler* phandler,
241 uint32_t id = 0,
242 MessageData* pdata = nullptr,
243 bool time_sensitive = false);
244 virtual void PostDelayed(const Location& posted_from,
245 int cmsDelay,
246 MessageHandler* phandler,
247 uint32_t id = 0,
248 MessageData* pdata = nullptr);
249 virtual void PostAt(const Location& posted_from,
250 int64_t tstamp,
251 MessageHandler* phandler,
252 uint32_t id = 0,
253 MessageData* pdata = nullptr);
254 // TODO(honghaiz): Remove this when all the dependencies are removed.
255 virtual void PostAt(const Location& posted_from,
256 uint32_t tstamp,
257 MessageHandler* phandler,
258 uint32_t id = 0,
259 MessageData* pdata = nullptr);
260 virtual void Clear(MessageHandler* phandler,
261 uint32_t id = MQID_ANY,
262 MessageList* removed = nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200263 virtual void Dispatch(Message* pmsg);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200264 virtual void ReceiveSends();
265
266 // Amount of time until the next message can be retrieved
267 virtual int GetDelay();
268
269 bool empty() const { return size() == 0u; }
270 size_t size() const {
271 CritScope cs(&crit_); // msgq_.size() is not thread safe.
272 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
273 }
274
275 // Internally posts a message which causes the doomed object to be deleted
Yves Gerey665174f2018-06-19 15:03:05 +0200276 template <class T>
277 void Dispose(T* doomed) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200278 if (doomed) {
279 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
280 }
281 }
282
283 // When this signal is sent out, any references to this queue should
284 // no longer be used.
285 sigslot::signal0<> SignalQueueDestroyed;
286
287 protected:
288 class PriorityQueue : public std::priority_queue<DelayedMessage> {
289 public:
290 container_type& container() { return c; }
291 void reheap() { make_heap(c.begin(), c.end(), comp); }
292 };
293
294 void DoDelayPost(const Location& posted_from,
295 int64_t cmsDelay,
296 int64_t tstamp,
297 MessageHandler* phandler,
298 uint32_t id,
299 MessageData* pdata);
300
301 // Perform initialization, subclasses must call this from their constructor
302 // if false was passed as init_queue to the MessageQueue constructor.
303 void DoInit();
304
305 // Perform cleanup, subclasses that override Clear must call this from the
306 // destructor.
307 void DoDestroy();
308
309 void WakeUpSocketServer();
310
311 bool fPeekKeep_;
312 Message msgPeek_;
danilchap3c6abd22017-09-06 05:46:29 -0700313 MessageList msgq_ RTC_GUARDED_BY(crit_);
314 PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
315 uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200316 CriticalSection crit_;
317 bool fInitialized_;
318 bool fDestroyed_;
319
320 private:
321 volatile int stop_;
322
323 // The SocketServer might not be owned by MessageQueue.
324 SocketServer* const ss_;
325 // Used if SocketServer ownership lies with |this|.
326 std::unique_ptr<SocketServer> own_ss_;
327
328 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
329};
330
331} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200333#endif // RTC_BASE_MESSAGEQUEUE_H_