blob: 429a56a8c1e3cd69f6dcafa1b19fbc90dfa51f03 [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
11#ifndef WEBRTC_BASE_MESSAGEQUEUE_H_
12#define WEBRTC_BASE_MESSAGEQUEUE_H_
13
14#include <string.h>
15
16#include <algorithm>
17#include <list>
jbauch555604a2016-04-26 03:13:22 -070018#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include <queue>
20#include <vector>
21
22#include "webrtc/base/basictypes.h"
23#include "webrtc/base/constructormagic.h"
24#include "webrtc/base/criticalsection.h"
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -070025#include "webrtc/base/location.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include "webrtc/base/messagehandler.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027#include "webrtc/base/scoped_ref_ptr.h"
jbauch9ccedc32016-02-25 01:14:56 -080028#include "webrtc/base/sharedexclusivelock.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029#include "webrtc/base/sigslot.h"
30#include "webrtc/base/socketserver.h"
31#include "webrtc/base/timeutils.h"
jbauch9ccedc32016-02-25 01:14:56 -080032#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033
34namespace rtc {
35
36struct Message;
37class MessageQueue;
38
39// MessageQueueManager does cleanup of of message queues
40
deadbeeff5f03e82016-06-06 11:16:06 -070041class MessageQueueManager {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042 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
Taylor Brandstetterb3c68102016-05-27 14:15:43 -070053 // Mainly for testing purposes, for use with a simulated clock.
deadbeeff5f03e82016-06-06 11:16:06 -070054 // Ensures that all message queues have processed delayed messages
55 // up until the current point in time.
56 static void ProcessAllMessageQueues();
Taylor Brandstetterb3c68102016-05-27 14:15:43 -070057
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058 private:
59 static MessageQueueManager* Instance();
60
61 MessageQueueManager();
deadbeeff5f03e82016-06-06 11:16:06 -070062 ~MessageQueueManager();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
64 void AddInternal(MessageQueue *message_queue);
65 void RemoveInternal(MessageQueue *message_queue);
66 void ClearInternal(MessageHandler *handler);
deadbeeff5f03e82016-06-06 11:16:06 -070067 void ProcessAllMessageQueuesInternal();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068
69 static MessageQueueManager* instance_;
henrike@webrtc.org99b41622014-05-21 20:42:17 +000070 // This list contains all live MessageQueues.
andrespcdf61722016-07-08 02:45:40 -070071 std::vector<MessageQueue*> message_queues_ GUARDED_BY(crit_);
72
73 // Acquire this with DebugNonReentrantCritScope.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074 CriticalSection crit_;
andrespcdf61722016-07-08 02:45:40 -070075 bool locked_ GUARDED_BY(crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076};
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
aleloie04064d2017-01-24 01:20:39 -080097// Like TypedMessageData, but for pointers that require a delete.
98template <class T>
99class ScopedMessageData : public MessageData {
100 public:
deadbeef884a7282017-02-17 15:57:05 -0800101 explicit ScopedMessageData(T* data) : data_(data) { }
102 const std::unique_ptr<T>& data() const { return data_; }
103 std::unique_ptr<T>& data() { return data_; }
aleloie04064d2017-01-24 01:20:39 -0800104
105 private:
106 std::unique_ptr<T> data_;
107};
108
109// Like ScopedMessageData, but for reference counted pointers.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000110template <class T>
111class ScopedRefMessageData : public MessageData {
112 public:
113 explicit ScopedRefMessageData(T* data) : data_(data) { }
114 const scoped_refptr<T>& data() const { return data_; }
115 scoped_refptr<T>& data() { return data_; }
116 private:
117 scoped_refptr<T> data_;
118};
119
120template<class T>
121inline MessageData* WrapMessageData(const T& data) {
122 return new TypedMessageData<T>(data);
123}
124
125template<class T>
126inline const T& UseMessageData(MessageData* data) {
127 return static_cast< TypedMessageData<T>* >(data)->data();
128}
129
130template<class T>
131class DisposeData : public MessageData {
132 public:
133 explicit DisposeData(T* data) : data_(data) { }
134 virtual ~DisposeData() { delete data_; }
135 private:
136 T* data_;
137};
138
Peter Boström0c4e06b2015-10-07 12:23:21 +0200139const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
140const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141
142// No destructor
143
144struct Message {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700145 Message()
146 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
Peter Boström0c4e06b2015-10-07 12:23:21 +0200147 inline bool Match(MessageHandler* handler, uint32_t id) const {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 return (handler == NULL || handler == phandler)
149 && (id == MQID_ANY || id == message_id);
150 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700151 Location posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152 MessageHandler *phandler;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200153 uint32_t message_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000154 MessageData *pdata;
Honghai Zhang82d78622016-05-06 11:29:15 -0700155 int64_t ts_sensitive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156};
157
158typedef std::list<Message> MessageList;
159
160// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
161// with the same trigger time are processed in num_ (FIFO) order.
162
163class DelayedMessage {
164 public:
Taylor Brandstetter2b3bf6b2016-05-19 14:57:31 -0700165 DelayedMessage(int64_t delay,
166 int64_t trigger,
167 uint32_t num,
168 const Message& msg)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200169 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170
171 bool operator< (const DelayedMessage& dmsg) const {
172 return (dmsg.msTrigger_ < msTrigger_)
173 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
174 }
175
Taylor Brandstetter2b3bf6b2016-05-19 14:57:31 -0700176 int64_t cmsDelay_; // for debugging
Honghai Zhang82d78622016-05-06 11:29:15 -0700177 int64_t msTrigger_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200178 uint32_t num_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 Message msg_;
180};
181
182class MessageQueue {
183 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +0000184 static const int kForever = -1;
185
jbauch25d1f282016-02-05 00:25:02 -0800186 // Create a new MessageQueue and optionally assign it to the passed
187 // SocketServer. Subclasses that override Clear should pass false for
188 // init_queue and call DoInit() from their constructor to prevent races
189 // with the MessageQueueManager using the object while the vtable is still
190 // being created.
danilchapbebf54c2016-04-28 01:32:48 -0700191 MessageQueue(SocketServer* ss, bool init_queue);
192 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
jbauch25d1f282016-02-05 00:25:02 -0800193
194 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
195 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
196 // between the destructor modifying the vtable, and the MessageQueueManager
197 // calling Clear on the object from a different thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 virtual ~MessageQueue();
199
jbauch9ccedc32016-02-25 01:14:56 -0800200 SocketServer* socketserver();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201 void set_socketserver(SocketServer* ss);
202
203 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
204 // futher Posts and Sends will fail. However, any pending Sends and *ready*
205 // Posts (as opposed to unexpired delayed Posts) will be delivered before
206 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
207 // we eliminate the race condition when an MessageHandler and MessageQueue
208 // may be destroyed independently of each other.
209 virtual void Quit();
210 virtual bool IsQuitting();
211 virtual void Restart();
pthatcher1749bc32017-02-08 13:18:00 -0800212 // Not all message queues actually process messages (such as SignalThread).
213 // In those cases, it's important to know, before posting, that it won't be
214 // Processed. Normally, this would be true until IsQuitting() is true.
215 virtual bool IsProcessingMessages();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216
217 // Get() will process I/O until:
218 // 1) A message is available (returns true)
219 // 2) cmsWait seconds have elapsed (returns false)
220 // 3) Stop() is called (returns false)
221 virtual bool Get(Message *pmsg, int cmsWait = kForever,
222 bool process_io = true);
223 virtual bool Peek(Message *pmsg, int cmsWait = 0);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700224 virtual void Post(const Location& posted_from,
225 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200226 uint32_t id = 0,
227 MessageData* pdata = NULL,
228 bool time_sensitive = false);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700229 virtual void PostDelayed(const Location& posted_from,
230 int cmsDelay,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000231 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200232 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000233 MessageData* pdata = NULL);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700234 virtual void PostAt(const Location& posted_from,
235 int64_t tstamp,
Honghai Zhang82d78622016-05-06 11:29:15 -0700236 MessageHandler* phandler,
237 uint32_t id = 0,
238 MessageData* pdata = NULL);
239 // TODO(honghaiz): Remove this when all the dependencies are removed.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700240 virtual void PostAt(const Location& posted_from,
241 uint32_t tstamp,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000242 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200243 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000244 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200245 virtual void Clear(MessageHandler* phandler,
246 uint32_t id = MQID_ANY,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 MessageList* removed = NULL);
248 virtual void Dispatch(Message *pmsg);
249 virtual void ReceiveSends();
250
251 // Amount of time until the next message can be retrieved
252 virtual int GetDelay();
253
254 bool empty() const { return size() == 0u; }
255 size_t size() const {
256 CritScope cs(&crit_); // msgq_.size() is not thread safe.
257 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
258 }
259
260 // Internally posts a message which causes the doomed object to be deleted
261 template<class T> void Dispose(T* doomed) {
262 if (doomed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700263 Post(RTC_FROM_HERE, NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 }
265 }
266
267 // When this signal is sent out, any references to this queue should
268 // no longer be used.
269 sigslot::signal0<> SignalQueueDestroyed;
270
271 protected:
272 class PriorityQueue : public std::priority_queue<DelayedMessage> {
273 public:
274 container_type& container() { return c; }
275 void reheap() { make_heap(c.begin(), c.end(), comp); }
276 };
277
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700278 void DoDelayPost(const Location& posted_from,
279 int64_t cmsDelay,
Honghai Zhang82d78622016-05-06 11:29:15 -0700280 int64_t tstamp,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200281 MessageHandler* phandler,
282 uint32_t id,
283 MessageData* pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284
jbauch25d1f282016-02-05 00:25:02 -0800285 // Perform initialization, subclasses must call this from their constructor
286 // if false was passed as init_queue to the MessageQueue constructor.
287 void DoInit();
288
289 // Perform cleanup, subclasses that override Clear must call this from the
290 // destructor.
291 void DoDestroy();
292
jbauch9ccedc32016-02-25 01:14:56 -0800293 void WakeUpSocketServer();
294
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 bool fPeekKeep_;
296 Message msgPeek_;
jbauch9ccedc32016-02-25 01:14:56 -0800297 MessageList msgq_ GUARDED_BY(crit_);
298 PriorityQueue dmsgq_ GUARDED_BY(crit_);
299 uint32_t dmsgq_next_num_ GUARDED_BY(crit_);
pbos5ad935c2016-01-25 03:52:44 -0800300 CriticalSection crit_;
jbauch25d1f282016-02-05 00:25:02 -0800301 bool fInitialized_;
302 bool fDestroyed_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303
304 private:
André Susano Pinto02a57972016-07-22 13:30:05 +0200305 volatile int stop_;
306
danilchapbebf54c2016-04-28 01:32:48 -0700307 // The SocketServer might not be owned by MessageQueue.
jbauch9ccedc32016-02-25 01:14:56 -0800308 SocketServer* ss_ GUARDED_BY(ss_lock_);
danilchapbebf54c2016-04-28 01:32:48 -0700309 // Used if SocketServer ownership lies with |this|.
310 std::unique_ptr<SocketServer> own_ss_;
jbauch9ccedc32016-02-25 01:14:56 -0800311 SharedExclusiveLock ss_lock_;
312
danilchapbebf54c2016-04-28 01:32:48 -0700313 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314};
315
316} // namespace rtc
317
318#endif // WEBRTC_BASE_MESSAGEQUEUE_H_