Loop.hxx 5.55 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifndef MPD_EVENT_LOOP_HXX
#define MPD_EVENT_LOOP_HXX

#include "check.h"
24
#include "thread/Id.hxx"
25
#include "util/Compiler.h"
26

27
#include "PollGroup.hxx"
28 29 30
#include "thread/Mutex.hxx"
#include "WakeFD.hxx"
#include "SocketMonitor.hxx"
31
#include "TimerEvent.hxx"
32
#include "IdleMonitor.hxx"
33
#include "DeferEvent.hxx"
34 35

#include <boost/intrusive/set.hpp>
36
#include <boost/intrusive/list.hpp>
37

38
#include <chrono>
39
#include <atomic>
40

41 42
#include <assert.h>

43 44 45 46 47 48 49
/**
 * An event loop that polls for events on file/socket descriptors.
 *
 * This class is not thread-safe, all methods must be called from the
 * thread that runs it, except where explicitly documented as
 * thread-safe.
 *
50
 * @see SocketMonitor, MultiSocketMonitor, TimerEvent, IdleMonitor
51
 */
52
class EventLoop final : SocketMonitor
53
{
54
	WakeFD wake_fd;
55

56
	struct TimerCompare {
57 58
		constexpr bool operator()(const TimerEvent &a,
					  const TimerEvent &b) const {
59 60
			return a.due < b.due;
		}
61 62
	};

63 64 65 66
	typedef boost::intrusive::multiset<TimerEvent,
					   boost::intrusive::member_hook<TimerEvent,
									 TimerEvent::TimerSetHook,
									 &TimerEvent::timer_set_hook>,
67 68 69
					   boost::intrusive::compare<TimerCompare>,
					   boost::intrusive::constant_time_size<false>> TimerSet;
	TimerSet timers;
70

71 72 73 74 75 76
	typedef boost::intrusive::list<IdleMonitor,
				       boost::intrusive::member_hook<IdleMonitor,
								     IdleMonitor::ListHook,
								     &IdleMonitor::list_hook>,
				       boost::intrusive::constant_time_size<false>> IdleList;
	IdleList idle;
77 78

	Mutex mutex;
79

80 81 82 83
	typedef boost::intrusive::list<DeferEvent,
				       boost::intrusive::member_hook<DeferEvent,
								     DeferEvent::ListHook,
								     &DeferEvent::list_hook>,
84 85
				       boost::intrusive::constant_time_size<false>> DeferredList;
	DeferredList deferred;
86

87
	std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
88

89
	std::atomic_bool quit;
90

91 92 93 94 95
	/**
	 * If this is true, then Run() has returned.
	 */
	std::atomic_bool dead;

96 97 98 99 100 101
	/**
	 * True when the object has been modified and another check is
	 * necessary before going to sleep via PollGroup::ReadEvents().
	 */
	bool again;

102 103 104 105 106 107
	/**
	 * True when handling callbacks, false when waiting for I/O or
	 * timeout.
	 *
	 * Protected with #mutex.
	 */
108
	bool busy = true;
109

110 111
	PollGroup poll_group;
	PollResult poll_result;
112

113 114 115
	/**
	 * A reference to the thread that is currently inside Run().
	 */
116
	ThreadId thread = ThreadId::Null();
117

118
public:
119 120 121
	/**
	 * Throws on error.
	 */
122
	explicit EventLoop(ThreadId _thread);
123

124 125
	EventLoop():EventLoop(ThreadId::GetCurrent()) {}

126
	~EventLoop() noexcept;
127

128
	/**
129
	 * A caching wrapper for std::chrono::steady_clock::now().
130
	 */
131
	std::chrono::steady_clock::time_point GetTime() const {
132 133
		assert(IsInside());

134
		return now;
135 136
	}

137 138 139 140 141
	/**
	 * Stop execution of this #EventLoop at the next chance.  This
	 * method is thread-safe and non-blocking: after returning, it
	 * is not guaranteed that the EventLoop has really stopped.
	 */
142
	void Break() noexcept;
143

144
	bool AddFD(int _fd, unsigned flags, SocketMonitor &m) noexcept {
145
		assert(IsInside());
146

147
		return poll_group.Add(_fd, flags, &m);
148 149
	}

150
	bool ModifyFD(int _fd, unsigned flags, SocketMonitor &m) noexcept {
151 152
		assert(IsInside());

153
		return poll_group.Modify(_fd, flags, &m);
154 155
	}

156 157 158 159 160
	/**
	 * Remove the given #SocketMonitor after the file descriptor
	 * has been closed.  This is like RemoveFD(), but does not
	 * attempt to use #EPOLL_CTL_DEL.
	 */
161
	bool Abandon(int fd, SocketMonitor &m) noexcept;
162

163
	bool RemoveFD(int fd, SocketMonitor &m) noexcept;
164

165 166
	void AddIdle(IdleMonitor &i) noexcept;
	void RemoveIdle(IdleMonitor &i) noexcept;
167

168
	void AddTimer(TimerEvent &t,
169 170
		      std::chrono::steady_clock::duration d) noexcept;
	void CancelTimer(TimerEvent &t) noexcept;
171

172
	/**
173
	 * Schedule a call to DeferEvent::RunDeferred().
174 175 176
	 *
	 * This method is thread-safe.
	 */
177
	void AddDeferred(DeferEvent &d) noexcept;
178 179

	/**
180
	 * Cancel a pending call to DeferEvent::RunDeferred().
181 182 183 184
	 * However after returning, the call may still be running.
	 *
	 * This method is thread-safe.
	 */
185
	void RemoveDeferred(DeferEvent &d) noexcept;
186

187 188 189 190
	/**
	 * The main function of this class.  It will loop until
	 * Break() gets called.  Can be called only once.
	 */
191
	void Run() noexcept;
192 193

private:
194
	/**
195
	 * Invoke all pending DeferEvents.
196 197 198
	 *
	 * Caller must lock the mutex.
	 */
199
	void HandleDeferred() noexcept;
200

201 202 203 204 205 206 207
	/**
	 * Invoke all expired #TimerEvent instances and return the
	 * duration until the next timer expires.  Returns a negative
	 * duration if there is no timeout.
	 */
	std::chrono::steady_clock::duration HandleTimers() noexcept;

208
	bool OnSocketReady(unsigned flags) noexcept override;
209 210

public:
211 212 213 214
	gcc_pure
	bool IsDead() const noexcept {
		return dead;
	}
215 216 217 218 219

	/**
	 * Are we currently running inside this EventLoop's thread?
	 */
	gcc_pure
220
	bool IsInside() const noexcept {
221 222
		return thread.IsInside();
	}
223 224 225
};

#endif /* MAIN_NOTIFY_H */