blob: c8e247da474239b45cd46ee8b04403883be320c2 [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
Henrik Kjellanderc0362762017-06-29 08:03:04 +020011#ifndef WEBRTC_RTC_BASE_MESSAGEQUEUE_H_
12#define WEBRTC_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
Henrik Kjellander00725112017-06-30 15:14:45 +020023#include "webrtc/base/basictypes.h"
24#include "webrtc/base/constructormagic.h"
25#include "webrtc/base/criticalsection.h"
26#include "webrtc/base/location.h"
27#include "webrtc/base/messagehandler.h"
28#include "webrtc/base/scoped_ref_ptr.h"
29#include "webrtc/base/sigslot.h"
30#include "webrtc/base/socketserver.h"
31#include "webrtc/base/timeutils.h"
32#include "webrtc/base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020033
34namespace rtc {
35
36struct Message;
37class MessageQueue;
38
39// MessageQueueManager does cleanup of of message queues
40
41class 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
73 // Acquire this with DebugNonReentrantCritScope.
74 CriticalSection crit_;
75 bool locked_ GUARDED_BY(crit_);
76};
77
78// Derive from this for specialized data
79// App manages lifetime, except when messages are purged
80
81class MessageData {
82 public:
83 MessageData() {}
84 virtual ~MessageData() {}
85};
86
87template <class T>
88class TypedMessageData : public MessageData {
89 public:
90 explicit TypedMessageData(const T& data) : data_(data) { }
91 const T& data() const { return data_; }
92 T& data() { return data_; }
93 private:
94 T data_;
95};
96
97// Like TypedMessageData, but for pointers that require a delete.
98template <class T>
99class ScopedMessageData : public MessageData {
100 public:
101 explicit ScopedMessageData(std::unique_ptr<T> data)
102 : data_(std::move(data)) {}
103 // Deprecated.
104 // TODO(deadbeef): Remove this once downstream applications stop using it.
105 explicit ScopedMessageData(T* data) : data_(data) {}
106 // Deprecated.
107 // TODO(deadbeef): Returning a reference to a unique ptr? Why. Get rid of
108 // this once downstream applications stop using it, then rename inner_data to
109 // just data.
110 const std::unique_ptr<T>& data() const { return data_; }
111 std::unique_ptr<T>& data() { return data_; }
112
113 const T& inner_data() const { return *data_; }
114 T& inner_data() { return *data_; }
115
116 private:
117 std::unique_ptr<T> data_;
118};
119
120// Like ScopedMessageData, but for reference counted pointers.
121template <class T>
122class ScopedRefMessageData : public MessageData {
123 public:
124 explicit ScopedRefMessageData(T* data) : data_(data) { }
125 const scoped_refptr<T>& data() const { return data_; }
126 scoped_refptr<T>& data() { return data_; }
127 private:
128 scoped_refptr<T> data_;
129};
130
131template<class T>
132inline MessageData* WrapMessageData(const T& data) {
133 return new TypedMessageData<T>(data);
134}
135
136template<class T>
137inline const T& UseMessageData(MessageData* data) {
138 return static_cast< TypedMessageData<T>* >(data)->data();
139}
140
141template<class T>
142class DisposeData : public MessageData {
143 public:
144 explicit DisposeData(T* data) : data_(data) { }
145 virtual ~DisposeData() { delete data_; }
146 private:
147 T* data_;
148};
149
nissebc8feda2017-06-29 06:21:20 -0700150// TODO(nisse): Replace RunnableData and FunctorData by a subclass of Message
151// owning a QueuedTask.
152class RunnableData : public MessageData {
153 public:
154 virtual void Run() = 0;
155};
156
157template <class FunctorT>
158class FunctorData : public RunnableData {
159 public:
160 explicit FunctorData(FunctorT functor) : functor_(std::move(functor)) {}
161 void Run() override { functor_(); }
162
163 private:
164 FunctorT functor_;
165};
166
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200167const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
168const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
169
170// No destructor
171
172struct Message {
173 Message()
174 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
175 inline bool Match(MessageHandler* handler, uint32_t id) const {
176 return (handler == nullptr || handler == phandler) &&
177 (id == MQID_ANY || id == message_id);
178 }
179 Location posted_from;
180 MessageHandler *phandler;
181 uint32_t message_id;
182 MessageData *pdata;
183 int64_t ts_sensitive;
184};
185
186typedef std::list<Message> MessageList;
187
188// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
189// with the same trigger time are processed in num_ (FIFO) order.
190
191class DelayedMessage {
192 public:
193 DelayedMessage(int64_t delay,
194 int64_t trigger,
195 uint32_t num,
196 const Message& msg)
197 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
198
199 bool operator< (const DelayedMessage& dmsg) const {
200 return (dmsg.msTrigger_ < msTrigger_)
201 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
202 }
203
204 int64_t cmsDelay_; // for debugging
205 int64_t msTrigger_;
206 uint32_t num_;
207 Message msg_;
208};
209
210class MessageQueue {
211 public:
212 static const int kForever = -1;
213
214 // Create a new MessageQueue and optionally assign it to the passed
215 // SocketServer. Subclasses that override Clear should pass false for
216 // init_queue and call DoInit() from their constructor to prevent races
217 // with the MessageQueueManager using the object while the vtable is still
218 // being created.
219 MessageQueue(SocketServer* ss, bool init_queue);
220 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
221
222 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
223 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
224 // between the destructor modifying the vtable, and the MessageQueueManager
225 // calling Clear on the object from a different thread.
226 virtual ~MessageQueue();
227
228 SocketServer* socketserver();
229
230 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
231 // futher Posts and Sends will fail. However, any pending Sends and *ready*
232 // Posts (as opposed to unexpired delayed Posts) will be delivered before
233 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
234 // we eliminate the race condition when an MessageHandler and MessageQueue
235 // may be destroyed independently of each other.
236 virtual void Quit();
237 virtual bool IsQuitting();
238 virtual void Restart();
239 // Not all message queues actually process messages (such as SignalThread).
240 // In those cases, it's important to know, before posting, that it won't be
241 // Processed. Normally, this would be true until IsQuitting() is true.
242 virtual bool IsProcessingMessages();
243
244 // Get() will process I/O until:
245 // 1) A message is available (returns true)
246 // 2) cmsWait seconds have elapsed (returns false)
247 // 3) Stop() is called (returns false)
248 virtual bool Get(Message *pmsg, int cmsWait = kForever,
249 bool process_io = true);
250 virtual bool Peek(Message *pmsg, int cmsWait = 0);
251 virtual void Post(const Location& posted_from,
252 MessageHandler* phandler,
253 uint32_t id = 0,
254 MessageData* pdata = nullptr,
255 bool time_sensitive = false);
nissebc8feda2017-06-29 06:21:20 -0700256
257 // TODO(nisse): Replace with a method for posting a
258 // std::unique_ptr<QueuedTask>, to ease gradual conversion to using TaskQueue.
259 template <class FunctorT,
260 // Additional type check, or else it collides with calls to the
261 // above Post method with the optional arguments omitted.
262 typename std::enable_if<!std::is_pointer<FunctorT>::value>::type* =
263 nullptr>
264 void Post(const Location& posted_from, FunctorT functor) {
265 PostFunctorInternal(posted_from,
266 new FunctorData<FunctorT>(std::move(functor)));
267 }
268
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200269 virtual void PostDelayed(const Location& posted_from,
270 int cmsDelay,
271 MessageHandler* phandler,
272 uint32_t id = 0,
273 MessageData* pdata = nullptr);
274 virtual void PostAt(const Location& posted_from,
275 int64_t tstamp,
276 MessageHandler* phandler,
277 uint32_t id = 0,
278 MessageData* pdata = nullptr);
279 // TODO(honghaiz): Remove this when all the dependencies are removed.
280 virtual void PostAt(const Location& posted_from,
281 uint32_t tstamp,
282 MessageHandler* phandler,
283 uint32_t id = 0,
284 MessageData* pdata = nullptr);
285 virtual void Clear(MessageHandler* phandler,
286 uint32_t id = MQID_ANY,
287 MessageList* removed = nullptr);
288 virtual void Dispatch(Message *pmsg);
289 virtual void ReceiveSends();
290
291 // Amount of time until the next message can be retrieved
292 virtual int GetDelay();
293
294 bool empty() const { return size() == 0u; }
295 size_t size() const {
296 CritScope cs(&crit_); // msgq_.size() is not thread safe.
297 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
298 }
299
300 // Internally posts a message which causes the doomed object to be deleted
301 template<class T> void Dispose(T* doomed) {
302 if (doomed) {
303 Post(RTC_FROM_HERE, nullptr, MQID_DISPOSE, new DisposeData<T>(doomed));
304 }
305 }
306
307 // When this signal is sent out, any references to this queue should
308 // no longer be used.
309 sigslot::signal0<> SignalQueueDestroyed;
310
311 protected:
312 class PriorityQueue : public std::priority_queue<DelayedMessage> {
313 public:
314 container_type& container() { return c; }
315 void reheap() { make_heap(c.begin(), c.end(), comp); }
316 };
317
318 void DoDelayPost(const Location& posted_from,
319 int64_t cmsDelay,
320 int64_t tstamp,
321 MessageHandler* phandler,
322 uint32_t id,
323 MessageData* pdata);
324
325 // Perform initialization, subclasses must call this from their constructor
326 // if false was passed as init_queue to the MessageQueue constructor.
327 void DoInit();
328
329 // Perform cleanup, subclasses that override Clear must call this from the
330 // destructor.
331 void DoDestroy();
332
333 void WakeUpSocketServer();
334
335 bool fPeekKeep_;
336 Message msgPeek_;
337 MessageList msgq_ GUARDED_BY(crit_);
338 PriorityQueue dmsgq_ GUARDED_BY(crit_);
339 uint32_t dmsgq_next_num_ GUARDED_BY(crit_);
340 CriticalSection crit_;
341 bool fInitialized_;
342 bool fDestroyed_;
343
344 private:
nissebc8feda2017-06-29 06:21:20 -0700345 void PostFunctorInternal(const Location& posted_from,
346 RunnableData* message_data);
347
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200348 volatile int stop_;
349
350 // The SocketServer might not be owned by MessageQueue.
351 SocketServer* const ss_;
352 // Used if SocketServer ownership lies with |this|.
353 std::unique_ptr<SocketServer> own_ss_;
354
355 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
356};
357
358} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359
Henrik Kjellanderc0362762017-06-29 08:03:04 +0200360#endif // WEBRTC_RTC_BASE_MESSAGEQUEUE_H_