summaryrefslogtreecommitdiffstats
blob: 297549e51ca7461e8d3f500ddb9dc0bb8b4c22e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (c) 2010-2015 Isode Limited.
 * All rights reserved.
 * See the COPYING file for more information.
 */

#pragma once

#include <deque>

#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>

#include <Swiften/Base/API.h>
#include <Swiften/EventLoop/EventLoop.h>

namespace Swift {
	class SWIFTEN_API DummyEventLoop : public EventLoop {
		public:
			DummyEventLoop();
			virtual ~DummyEventLoop();

			void processEvents() {
				while (hasEvents()) {
					/* 
					  Creating a copy of the to-be-handled Event object because handling
					  it can result in a DummyEventLoop::post() call.
					  This call would also try to lock the eventsMutex_, resulting in a 
					  deadlock. 
					*/

					eventsMutex_.lock();
					Event eventCopy = events_[0];
					eventsMutex_.unlock();

					handleEvent(eventCopy);

					{
						boost::lock_guard<boost::mutex> lock(eventsMutex_);
						events_.pop_front();
					}
				}
			}

			bool hasEvents() {
				boost::lock_guard<boost::mutex> lock(eventsMutex_);
				return !events_.empty();
			}

			virtual void post(const Event& event) {
				boost::lock_guard<boost::mutex> lock(eventsMutex_);
				events_.push_back(event);
			}

		private:
			boost::mutex eventsMutex_;
			std::deque<Event> events_;
	};
}