blob: efc479cf2644243d8abff92dcfe414e43055d97b [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>
18#include <queue>
19#include <vector>
20
21#include "webrtc/base/basictypes.h"
22#include "webrtc/base/constructormagic.h"
23#include "webrtc/base/criticalsection.h"
24#include "webrtc/base/messagehandler.h"
25#include "webrtc/base/scoped_ptr.h"
26#include "webrtc/base/scoped_ref_ptr.h"
jbauch9ccedc32016-02-25 01:14:56 -080027#include "webrtc/base/sharedexclusivelock.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028#include "webrtc/base/sigslot.h"
29#include "webrtc/base/socketserver.h"
30#include "webrtc/base/timeutils.h"
jbauch9ccedc32016-02-25 01:14:56 -080031#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032
33namespace rtc {
34
35struct Message;
36class MessageQueue;
37
38// MessageQueueManager does cleanup of of message queues
39
40class MessageQueueManager {
41 public:
42 static void Add(MessageQueue *message_queue);
43 static void Remove(MessageQueue *message_queue);
44 static void Clear(MessageHandler *handler);
45
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 private:
53 static MessageQueueManager* Instance();
54
55 MessageQueueManager();
56 ~MessageQueueManager();
57
58 void AddInternal(MessageQueue *message_queue);
59 void RemoveInternal(MessageQueue *message_queue);
60 void ClearInternal(MessageHandler *handler);
61
62 static MessageQueueManager* instance_;
henrike@webrtc.org99b41622014-05-21 20:42:17 +000063 // This list contains all live MessageQueues.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064 std::vector<MessageQueue *> message_queues_;
65 CriticalSection crit_;
66};
67
68// Derive from this for specialized data
69// App manages lifetime, except when messages are purged
70
71class MessageData {
72 public:
73 MessageData() {}
74 virtual ~MessageData() {}
75};
76
77template <class T>
78class TypedMessageData : public MessageData {
79 public:
80 explicit TypedMessageData(const T& data) : data_(data) { }
81 const T& data() const { return data_; }
82 T& data() { return data_; }
83 private:
84 T data_;
85};
86
87// Like TypedMessageData, but for pointers that require a delete.
88template <class T>
89class ScopedMessageData : public MessageData {
90 public:
91 explicit ScopedMessageData(T* data) : data_(data) { }
92 const scoped_ptr<T>& data() const { return data_; }
93 scoped_ptr<T>& data() { return data_; }
94 private:
95 scoped_ptr<T> data_;
96};
97
98// Like ScopedMessageData, but for reference counted pointers.
99template <class T>
100class ScopedRefMessageData : public MessageData {
101 public:
102 explicit ScopedRefMessageData(T* data) : data_(data) { }
103 const scoped_refptr<T>& data() const { return data_; }
104 scoped_refptr<T>& data() { return data_; }
105 private:
106 scoped_refptr<T> data_;
107};
108
109template<class T>
110inline MessageData* WrapMessageData(const T& data) {
111 return new TypedMessageData<T>(data);
112}
113
114template<class T>
115inline const T& UseMessageData(MessageData* data) {
116 return static_cast< TypedMessageData<T>* >(data)->data();
117}
118
119template<class T>
120class DisposeData : public MessageData {
121 public:
122 explicit DisposeData(T* data) : data_(data) { }
123 virtual ~DisposeData() { delete data_; }
124 private:
125 T* data_;
126};
127
Peter Boström0c4e06b2015-10-07 12:23:21 +0200128const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
129const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130
131// No destructor
132
133struct Message {
134 Message() {
135 memset(this, 0, sizeof(*this));
136 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200137 inline bool Match(MessageHandler* handler, uint32_t id) const {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 return (handler == NULL || handler == phandler)
139 && (id == MQID_ANY || id == message_id);
140 }
141 MessageHandler *phandler;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200142 uint32_t message_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 MessageData *pdata;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200144 uint32_t ts_sensitive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145};
146
147typedef std::list<Message> MessageList;
148
149// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
150// with the same trigger time are processed in num_ (FIFO) order.
151
152class DelayedMessage {
153 public:
Peter Boström0c4e06b2015-10-07 12:23:21 +0200154 DelayedMessage(int delay, uint32_t trigger, uint32_t num, const Message& msg)
155 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000156
157 bool operator< (const DelayedMessage& dmsg) const {
158 return (dmsg.msTrigger_ < msTrigger_)
159 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
160 }
161
162 int cmsDelay_; // for debugging
Peter Boström0c4e06b2015-10-07 12:23:21 +0200163 uint32_t msTrigger_;
164 uint32_t num_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 Message msg_;
166};
167
168class MessageQueue {
169 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +0000170 static const int kForever = -1;
171
jbauch25d1f282016-02-05 00:25:02 -0800172 // Create a new MessageQueue and optionally assign it to the passed
173 // SocketServer. Subclasses that override Clear should pass false for
174 // init_queue and call DoInit() from their constructor to prevent races
175 // with the MessageQueueManager using the object while the vtable is still
176 // being created.
177 explicit MessageQueue(SocketServer* ss = NULL,
178 bool init_queue = true);
179
180 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
181 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
182 // between the destructor modifying the vtable, and the MessageQueueManager
183 // calling Clear on the object from a different thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184 virtual ~MessageQueue();
185
jbauch9ccedc32016-02-25 01:14:56 -0800186 SocketServer* socketserver();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187 void set_socketserver(SocketServer* ss);
188
189 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
190 // futher Posts and Sends will fail. However, any pending Sends and *ready*
191 // Posts (as opposed to unexpired delayed Posts) will be delivered before
192 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
193 // we eliminate the race condition when an MessageHandler and MessageQueue
194 // may be destroyed independently of each other.
195 virtual void Quit();
196 virtual bool IsQuitting();
197 virtual void Restart();
198
199 // Get() will process I/O until:
200 // 1) A message is available (returns true)
201 // 2) cmsWait seconds have elapsed (returns false)
202 // 3) Stop() is called (returns false)
203 virtual bool Get(Message *pmsg, int cmsWait = kForever,
204 bool process_io = true);
205 virtual bool Peek(Message *pmsg, int cmsWait = 0);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200206 virtual void Post(MessageHandler* phandler,
207 uint32_t id = 0,
208 MessageData* pdata = NULL,
209 bool time_sensitive = false);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000210 virtual void PostDelayed(int cmsDelay,
211 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000213 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200214 virtual void PostAt(uint32_t tstamp,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000215 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200216 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000217 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200218 virtual void Clear(MessageHandler* phandler,
219 uint32_t id = MQID_ANY,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220 MessageList* removed = NULL);
221 virtual void Dispatch(Message *pmsg);
222 virtual void ReceiveSends();
223
224 // Amount of time until the next message can be retrieved
225 virtual int GetDelay();
226
227 bool empty() const { return size() == 0u; }
228 size_t size() const {
229 CritScope cs(&crit_); // msgq_.size() is not thread safe.
230 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
231 }
232
233 // Internally posts a message which causes the doomed object to be deleted
234 template<class T> void Dispose(T* doomed) {
235 if (doomed) {
236 Post(NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
237 }
238 }
239
240 // When this signal is sent out, any references to this queue should
241 // no longer be used.
242 sigslot::signal0<> SignalQueueDestroyed;
243
244 protected:
245 class PriorityQueue : public std::priority_queue<DelayedMessage> {
246 public:
247 container_type& container() { return c; }
248 void reheap() { make_heap(c.begin(), c.end(), comp); }
249 };
250
Peter Boström0c4e06b2015-10-07 12:23:21 +0200251 void DoDelayPost(int cmsDelay,
252 uint32_t tstamp,
253 MessageHandler* phandler,
254 uint32_t id,
255 MessageData* pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
jbauch25d1f282016-02-05 00:25:02 -0800257 // Perform initialization, subclasses must call this from their constructor
258 // if false was passed as init_queue to the MessageQueue constructor.
259 void DoInit();
260
261 // Perform cleanup, subclasses that override Clear must call this from the
262 // destructor.
263 void DoDestroy();
264
jbauch9ccedc32016-02-25 01:14:56 -0800265 void WakeUpSocketServer();
266
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 bool fStop_;
268 bool fPeekKeep_;
269 Message msgPeek_;
jbauch9ccedc32016-02-25 01:14:56 -0800270 MessageList msgq_ GUARDED_BY(crit_);
271 PriorityQueue dmsgq_ GUARDED_BY(crit_);
272 uint32_t dmsgq_next_num_ GUARDED_BY(crit_);
pbos5ad935c2016-01-25 03:52:44 -0800273 CriticalSection crit_;
jbauch25d1f282016-02-05 00:25:02 -0800274 bool fInitialized_;
275 bool fDestroyed_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276
277 private:
jbauch9ccedc32016-02-25 01:14:56 -0800278 // The SocketServer is not owned by MessageQueue.
279 SocketServer* ss_ GUARDED_BY(ss_lock_);
280 // If a server isn't supplied in the constructor, use this one.
281 scoped_ptr<SocketServer> default_ss_;
282 SharedExclusiveLock ss_lock_;
283
henrikg3c089d72015-09-16 05:37:44 -0700284 RTC_DISALLOW_COPY_AND_ASSIGN(MessageQueue);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285};
286
287} // namespace rtc
288
289#endif // WEBRTC_BASE_MESSAGEQUEUE_H_