blob: 14cf29bb28d87ffe5b011d7101b4ddc27157fc73 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000097template <class T>
98class ScopedRefMessageData : public MessageData {
99 public:
100 explicit ScopedRefMessageData(T* data) : data_(data) { }
101 const scoped_refptr<T>& data() const { return data_; }
102 scoped_refptr<T>& data() { return data_; }
103 private:
104 scoped_refptr<T> data_;
105};
106
107template<class T>
108inline MessageData* WrapMessageData(const T& data) {
109 return new TypedMessageData<T>(data);
110}
111
112template<class T>
113inline const T& UseMessageData(MessageData* data) {
114 return static_cast< TypedMessageData<T>* >(data)->data();
115}
116
117template<class T>
118class DisposeData : public MessageData {
119 public:
120 explicit DisposeData(T* data) : data_(data) { }
121 virtual ~DisposeData() { delete data_; }
122 private:
123 T* data_;
124};
125
Peter Boström0c4e06b2015-10-07 12:23:21 +0200126const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
127const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128
129// No destructor
130
131struct Message {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700132 Message()
133 : phandler(nullptr), message_id(0), pdata(nullptr), ts_sensitive(0) {}
Peter Boström0c4e06b2015-10-07 12:23:21 +0200134 inline bool Match(MessageHandler* handler, uint32_t id) const {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135 return (handler == NULL || handler == phandler)
136 && (id == MQID_ANY || id == message_id);
137 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700138 Location posted_from;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 MessageHandler *phandler;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200140 uint32_t message_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 MessageData *pdata;
Honghai Zhang82d78622016-05-06 11:29:15 -0700142 int64_t ts_sensitive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143};
144
145typedef std::list<Message> MessageList;
146
147// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
148// with the same trigger time are processed in num_ (FIFO) order.
149
150class DelayedMessage {
151 public:
Taylor Brandstetter2b3bf6b2016-05-19 14:57:31 -0700152 DelayedMessage(int64_t delay,
153 int64_t trigger,
154 uint32_t num,
155 const Message& msg)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200156 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157
158 bool operator< (const DelayedMessage& dmsg) const {
159 return (dmsg.msTrigger_ < msTrigger_)
160 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
161 }
162
Taylor Brandstetter2b3bf6b2016-05-19 14:57:31 -0700163 int64_t cmsDelay_; // for debugging
Honghai Zhang82d78622016-05-06 11:29:15 -0700164 int64_t msTrigger_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200165 uint32_t num_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 Message msg_;
167};
168
169class MessageQueue {
170 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +0000171 static const int kForever = -1;
172
jbauch25d1f282016-02-05 00:25:02 -0800173 // Create a new MessageQueue and optionally assign it to the passed
174 // SocketServer. Subclasses that override Clear should pass false for
175 // init_queue and call DoInit() from their constructor to prevent races
176 // with the MessageQueueManager using the object while the vtable is still
177 // being created.
danilchapbebf54c2016-04-28 01:32:48 -0700178 MessageQueue(SocketServer* ss, bool init_queue);
179 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
jbauch25d1f282016-02-05 00:25:02 -0800180
181 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
182 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
183 // between the destructor modifying the vtable, and the MessageQueueManager
184 // calling Clear on the object from a different thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 virtual ~MessageQueue();
186
jbauch9ccedc32016-02-25 01:14:56 -0800187 SocketServer* socketserver();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188 void set_socketserver(SocketServer* ss);
189
190 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
191 // futher Posts and Sends will fail. However, any pending Sends and *ready*
192 // Posts (as opposed to unexpired delayed Posts) will be delivered before
193 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
194 // we eliminate the race condition when an MessageHandler and MessageQueue
195 // may be destroyed independently of each other.
196 virtual void Quit();
197 virtual bool IsQuitting();
198 virtual void Restart();
199
200 // Get() will process I/O until:
201 // 1) A message is available (returns true)
202 // 2) cmsWait seconds have elapsed (returns false)
203 // 3) Stop() is called (returns false)
204 virtual bool Get(Message *pmsg, int cmsWait = kForever,
205 bool process_io = true);
206 virtual bool Peek(Message *pmsg, int cmsWait = 0);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700207 virtual void Post(const Location& posted_from,
208 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200209 uint32_t id = 0,
210 MessageData* pdata = NULL,
211 bool time_sensitive = false);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700212 virtual void PostDelayed(const Location& posted_from,
213 int cmsDelay,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000214 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200215 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000216 MessageData* pdata = NULL);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700217 virtual void PostAt(const Location& posted_from,
218 int64_t tstamp,
Honghai Zhang82d78622016-05-06 11:29:15 -0700219 MessageHandler* phandler,
220 uint32_t id = 0,
221 MessageData* pdata = NULL);
222 // TODO(honghaiz): Remove this when all the dependencies are removed.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700223 virtual void PostAt(const Location& posted_from,
224 uint32_t tstamp,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000225 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200226 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000227 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200228 virtual void Clear(MessageHandler* phandler,
229 uint32_t id = MQID_ANY,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000230 MessageList* removed = NULL);
231 virtual void Dispatch(Message *pmsg);
232 virtual void ReceiveSends();
233
234 // Amount of time until the next message can be retrieved
235 virtual int GetDelay();
236
237 bool empty() const { return size() == 0u; }
238 size_t size() const {
239 CritScope cs(&crit_); // msgq_.size() is not thread safe.
240 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
241 }
242
243 // Internally posts a message which causes the doomed object to be deleted
244 template<class T> void Dispose(T* doomed) {
245 if (doomed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700246 Post(RTC_FROM_HERE, NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 }
248 }
249
250 // When this signal is sent out, any references to this queue should
251 // no longer be used.
252 sigslot::signal0<> SignalQueueDestroyed;
253
254 protected:
255 class PriorityQueue : public std::priority_queue<DelayedMessage> {
256 public:
257 container_type& container() { return c; }
258 void reheap() { make_heap(c.begin(), c.end(), comp); }
259 };
260
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700261 void DoDelayPost(const Location& posted_from,
262 int64_t cmsDelay,
Honghai Zhang82d78622016-05-06 11:29:15 -0700263 int64_t tstamp,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200264 MessageHandler* phandler,
265 uint32_t id,
266 MessageData* pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267
jbauch25d1f282016-02-05 00:25:02 -0800268 // Perform initialization, subclasses must call this from their constructor
269 // if false was passed as init_queue to the MessageQueue constructor.
270 void DoInit();
271
272 // Perform cleanup, subclasses that override Clear must call this from the
273 // destructor.
274 void DoDestroy();
275
jbauch9ccedc32016-02-25 01:14:56 -0800276 void WakeUpSocketServer();
277
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 bool fPeekKeep_;
279 Message msgPeek_;
jbauch9ccedc32016-02-25 01:14:56 -0800280 MessageList msgq_ GUARDED_BY(crit_);
281 PriorityQueue dmsgq_ GUARDED_BY(crit_);
282 uint32_t dmsgq_next_num_ GUARDED_BY(crit_);
pbos5ad935c2016-01-25 03:52:44 -0800283 CriticalSection crit_;
jbauch25d1f282016-02-05 00:25:02 -0800284 bool fInitialized_;
285 bool fDestroyed_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286
287 private:
André Susano Pinto02a57972016-07-22 13:30:05 +0200288 volatile int stop_;
289
danilchapbebf54c2016-04-28 01:32:48 -0700290 // The SocketServer might not be owned by MessageQueue.
jbauch9ccedc32016-02-25 01:14:56 -0800291 SocketServer* ss_ GUARDED_BY(ss_lock_);
danilchapbebf54c2016-04-28 01:32:48 -0700292 // Used if SocketServer ownership lies with |this|.
293 std::unique_ptr<SocketServer> own_ss_;
jbauch9ccedc32016-02-25 01:14:56 -0800294 SharedExclusiveLock ss_lock_;
295
danilchapbebf54c2016-04-28 01:32:48 -0700296 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297};
298
299} // namespace rtc
300
301#endif // WEBRTC_BASE_MESSAGEQUEUE_H_