blob: d64ea86cbe918ec1df278088af6e30e47fc27dba [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
Niels Möller8909a632018-09-06 08:42:44 +020052 // TODO(nisse): Delete alias, as soon as downstream code is updated.
53 static void ProcessAllMessageQueues() { ProcessAllMessageQueuesForTesting(); }
54
55 // For testing purposes, for use with a simulated clock.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020056 // Ensures that all message queues have processed delayed messages
57 // up until the current point in time.
Niels Möller8909a632018-09-06 08:42:44 +020058 static void ProcessAllMessageQueuesForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020059
60 private:
61 static MessageQueueManager* Instance();
62
63 MessageQueueManager();
64 ~MessageQueueManager();
65
Yves Gerey665174f2018-06-19 15:03:05 +020066 void AddInternal(MessageQueue* message_queue);
67 void RemoveInternal(MessageQueue* message_queue);
68 void ClearInternal(MessageHandler* handler);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020069 void ProcessAllMessageQueuesInternal();
70
71 static MessageQueueManager* instance_;
72 // This list contains all live MessageQueues.
danilchap3c6abd22017-09-06 05:46:29 -070073 std::vector<MessageQueue*> message_queues_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020074
jbauch5b361732017-07-06 23:51:37 -070075 // Methods that don't modify the list of message queues may be called in a
76 // re-entrant fashion. "processing_" keeps track of the depth of re-entrant
77 // calls.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020078 CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -070079 size_t processing_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020080};
81
82// Derive from this for specialized data
83// App manages lifetime, except when messages are purged
84
85class MessageData {
86 public:
87 MessageData() {}
88 virtual ~MessageData() {}
89};
90
91template <class T>
92class TypedMessageData : public MessageData {
93 public:
Yves Gerey665174f2018-06-19 15:03:05 +020094 explicit TypedMessageData(const T& data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020095 const T& data() const { return data_; }
96 T& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +020097
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020098 private:
99 T data_;
100};
101
102// Like TypedMessageData, but for pointers that require a delete.
103template <class T>
104class ScopedMessageData : public MessageData {
105 public:
106 explicit ScopedMessageData(std::unique_ptr<T> data)
107 : data_(std::move(data)) {}
108 // Deprecated.
109 // TODO(deadbeef): Remove this once downstream applications stop using it.
110 explicit ScopedMessageData(T* data) : data_(data) {}
111 // Deprecated.
112 // TODO(deadbeef): Returning a reference to a unique ptr? Why. Get rid of
113 // this once downstream applications stop using it, then rename inner_data to
114 // just data.
115 const std::unique_ptr<T>& data() const { return data_; }
116 std::unique_ptr<T>& data() { return data_; }
117
118 const T& inner_data() const { return *data_; }
119 T& inner_data() { return *data_; }
120
121 private:
122 std::unique_ptr<T> data_;
123};
124
125// Like ScopedMessageData, but for reference counted pointers.
126template <class T>
127class ScopedRefMessageData : public MessageData {
128 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200129 explicit ScopedRefMessageData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200130 const scoped_refptr<T>& data() const { return data_; }
131 scoped_refptr<T>& data() { return data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200132
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200133 private:
134 scoped_refptr<T> data_;
135};
136
Yves Gerey665174f2018-06-19 15:03:05 +0200137template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200138inline MessageData* WrapMessageData(const T& data) {
139 return new TypedMessageData<T>(data);
140}
141
Yves Gerey665174f2018-06-19 15:03:05 +0200142template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200143inline const T& UseMessageData(MessageData* data) {
Yves Gerey665174f2018-06-19 15:03:05 +0200144 return static_cast<TypedMessageData<T>*>(data)->data();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145}
146
Yves Gerey665174f2018-06-19 15:03:05 +0200147template <class T>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148class DisposeData : public MessageData {
149 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200150 explicit DisposeData(T* data) : data_(data) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151 virtual ~DisposeData() { delete data_; }
Yves Gerey665174f2018-06-19 15:03:05 +0200152
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200153 private:
154 T* data_;
155};
156
157const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
158const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
159
160// No destructor
161
162struct Message {
163 Message()
164 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
165 inline bool Match(MessageHandler* handler, uint32_t id) const {
166 return (handler == nullptr || handler == phandler) &&
167 (id == MQID_ANY || id == message_id);
168 }
169 Location posted_from;
Yves Gerey665174f2018-06-19 15:03:05 +0200170 MessageHandler* phandler;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200171 uint32_t message_id;
Yves Gerey665174f2018-06-19 15:03:05 +0200172 MessageData* pdata;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200173 int64_t ts_sensitive;
174};
175
176typedef std::list<Message> MessageList;
177
178// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
179// with the same trigger time are processed in num_ (FIFO) order.
180
181class DelayedMessage {
182 public:
183 DelayedMessage(int64_t delay,
184 int64_t trigger,
185 uint32_t num,
186 const Message& msg)
187 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
188
Yves Gerey665174f2018-06-19 15:03:05 +0200189 bool operator<(const DelayedMessage& dmsg) const {
190 return (dmsg.msTrigger_ < msTrigger_) ||
191 ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200192 }
193
194 int64_t cmsDelay_; // for debugging
195 int64_t msTrigger_;
196 uint32_t num_;
197 Message msg_;
198};
199
200class MessageQueue {
201 public:
202 static const int kForever = -1;
203
204 // Create a new MessageQueue and optionally assign it to the passed
205 // SocketServer. Subclasses that override Clear should pass false for
206 // init_queue and call DoInit() from their constructor to prevent races
207 // with the MessageQueueManager using the object while the vtable is still
208 // being created.
209 MessageQueue(SocketServer* ss, bool init_queue);
210 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
211
212 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
213 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
214 // between the destructor modifying the vtable, and the MessageQueueManager
215 // calling Clear on the object from a different thread.
216 virtual ~MessageQueue();
217
218 SocketServer* socketserver();
219
220 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
221 // futher Posts and Sends will fail. However, any pending Sends and *ready*
222 // Posts (as opposed to unexpired delayed Posts) will be delivered before
223 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
224 // we eliminate the race condition when an MessageHandler and MessageQueue
225 // may be destroyed independently of each other.
226 virtual void Quit();
227 virtual bool IsQuitting();
228 virtual void Restart();
229 // Not all message queues actually process messages (such as SignalThread).
230 // In those cases, it's important to know, before posting, that it won't be
231 // Processed. Normally, this would be true until IsQuitting() is true.
Niels Möller8909a632018-09-06 08:42:44 +0200232 virtual bool IsProcessingMessagesForTesting();
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200233
234 // Get() will process I/O until:
235 // 1) A message is available (returns true)
236 // 2) cmsWait seconds have elapsed (returns false)
237 // 3) Stop() is called (returns false)
Yves Gerey665174f2018-06-19 15:03:05 +0200238 virtual bool Get(Message* pmsg,
239 int cmsWait = kForever,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200240 bool process_io = true);
Yves Gerey665174f2018-06-19 15:03:05 +0200241 virtual bool Peek(Message* pmsg, int cmsWait = 0);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200242 virtual void Post(const Location& posted_from,
243 MessageHandler* phandler,
244 uint32_t id = 0,
245 MessageData* pdata = nullptr,
246 bool time_sensitive = false);
247 virtual void PostDelayed(const Location& posted_from,
248 int cmsDelay,
249 MessageHandler* phandler,
250 uint32_t id = 0,
251 MessageData* pdata = nullptr);
252 virtual void PostAt(const Location& posted_from,
253 int64_t tstamp,
254 MessageHandler* phandler,
255 uint32_t id = 0,
256 MessageData* pdata = nullptr);
257 // TODO(honghaiz): Remove this when all the dependencies are removed.
258 virtual void PostAt(const Location& posted_from,
259 uint32_t tstamp,
260 MessageHandler* phandler,
261 uint32_t id = 0,
262 MessageData* pdata = nullptr);
263 virtual void Clear(MessageHandler* phandler,
264 uint32_t id = MQID_ANY,
265 MessageList* removed = nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200266 virtual void Dispatch(Message* pmsg);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200267 virtual void ReceiveSends();
268
269 // Amount of time until the next message can be retrieved
270 virtual int GetDelay();
271
272 bool empty() const { return size() == 0u; }
273 size_t size() const {
274 CritScope cs(&crit_); // msgq_.size() is not thread safe.
275 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
276 }
277
278 // Internally posts a message which causes the doomed object to be deleted
Yves Gerey665174f2018-06-19 15:03:05 +0200279 template <class T>
280 void Dispose(T* doomed) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200281 if (doomed) {
282 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
283 }
284 }
285
286 // When this signal is sent out, any references to this queue should
287 // no longer be used.
288 sigslot::signal0<> SignalQueueDestroyed;
289
290 protected:
291 class PriorityQueue : public std::priority_queue<DelayedMessage> {
292 public:
293 container_type& container() { return c; }
294 void reheap() { make_heap(c.begin(), c.end(), comp); }
295 };
296
297 void DoDelayPost(const Location& posted_from,
298 int64_t cmsDelay,
299 int64_t tstamp,
300 MessageHandler* phandler,
301 uint32_t id,
302 MessageData* pdata);
303
304 // Perform initialization, subclasses must call this from their constructor
305 // if false was passed as init_queue to the MessageQueue constructor.
306 void DoInit();
307
308 // Perform cleanup, subclasses that override Clear must call this from the
309 // destructor.
310 void DoDestroy();
311
312 void WakeUpSocketServer();
313
314 bool fPeekKeep_;
315 Message msgPeek_;
danilchap3c6abd22017-09-06 05:46:29 -0700316 MessageList msgq_ RTC_GUARDED_BY(crit_);
317 PriorityQueue dmsgq_ RTC_GUARDED_BY(crit_);
318 uint32_t dmsgq_next_num_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319 CriticalSection crit_;
320 bool fInitialized_;
321 bool fDestroyed_;
322
323 private:
324 volatile int stop_;
325
326 // The SocketServer might not be owned by MessageQueue.
327 SocketServer* const ss_;
328 // Used if SocketServer ownership lies with |this|.
329 std::unique_ptr<SocketServer> own_ss_;
330
331 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
332};
333
334} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200336#endif // RTC_BASE_MESSAGEQUEUE_H_