Loop.hxx 5.73 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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
 * 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

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

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

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

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

40 41
#include <assert.h>

42 43 44 45 46 47 48
/**
 * 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.
 *
49
 * @see SocketMonitor, MultiSocketMonitor, TimerEvent, IdleMonitor
50
 */
51
class EventLoop final : SocketMonitor
52
{
53
	WakeFD wake_fd;
54

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

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

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

	Mutex mutex;
78

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

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

88
	/**
89 90 91 92
	 * Is this #EventLoop alive, i.e. can events be scheduled?
	 * This is used by BlockingCall() to determine whether
	 * schedule in the #EventThread or to call directly (if
	 * there's no #EventThread yet/anymore).
93
	 */
94 95 96
	bool alive;

	std::atomic_bool quit;
97

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

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

112 113
	PollGroup poll_group;
	PollResult poll_result;
114

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

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

126 127
	EventLoop():EventLoop(ThreadId::GetCurrent()) {}

128
	~EventLoop() noexcept;
129

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

136
		return now;
137 138
	}

139 140 141 142 143
	/**
	 * 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.
	 */
144
	void Break() noexcept;
145

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

149
		return poll_group.Add(_fd, flags, &m);
150 151
	}

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

155
		return poll_group.Modify(_fd, flags, &m);
156 157
	}

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

165
	bool RemoveFD(int fd, SocketMonitor &m) noexcept;
166

167 168
	void AddIdle(IdleMonitor &i) noexcept;
	void RemoveIdle(IdleMonitor &i) noexcept;
169

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

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

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

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

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

203 204 205 206 207 208 209
	/**
	 * 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;

210
	bool OnSocketReady(unsigned flags) noexcept override;
211 212

public:
213 214 215 216 217 218
	void SetAlive(bool _alive) noexcept {
		alive = _alive;
	}

	bool IsAlive() const noexcept {
		return alive;
219
	}
220 221 222 223 224

	/**
	 * Are we currently running inside this EventLoop's thread?
	 */
	gcc_pure
225
	bool IsInside() const noexcept {
226 227
		return thread.IsInside();
	}
228 229 230
};

#endif /* MAIN_NOTIFY_H */