DeferEvent.hxx 2.03 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * 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.
 */

20 21
#ifndef MPD_DEFER_EVENT_HXX
#define MPD_DEFER_EVENT_HXX
22 23

#include "util/BindMethod.hxx"
24
#include "util/IntrusiveList.hxx"
25 26 27

class EventLoop;

28
/**
29 30 31
 * Defer execution until the next event loop iteration.  Use this to
 * move calls out of the current stack frame, to avoid surprising side
 * effects for callers up in the call chain.
32
 *
33 34
 * This class is not thread-safe, all methods must be called from the
 * thread that runs the #EventLoop.
35
 */
36
class DeferEvent final : AutoUnlinkIntrusiveListHook
37
{
38
	friend class EventLoop;
39
	friend class IntrusiveList<DeferEvent>;
40 41 42

	EventLoop &loop;

43
	using Callback = BoundMethod<void() noexcept>;
44 45 46
	const Callback callback;

public:
47 48
	DeferEvent(EventLoop &_loop, Callback _callback) noexcept
		:loop(_loop), callback(_callback) {}
49

50 51 52
	DeferEvent(const DeferEvent &) = delete;
	DeferEvent &operator=(const DeferEvent &) = delete;

53 54
	auto &GetEventLoop() const noexcept {
		return loop;
55 56
	}

57 58
	bool IsPending() const noexcept {
		return is_linked();
59 60 61
	}

	void Schedule() noexcept;
62

63 64 65 66 67 68
	/**
	 * Schedule this event, but only after the #EventLoop is idle,
	 * i.e. before going to sleep.
	 */
	void ScheduleIdle() noexcept;

69 70 71
	void Cancel() noexcept {
		if (IsPending())
			unlink();
72 73
	}

74 75
private:
	void Run() noexcept {
76 77 78 79 80
		callback();
	}
};

#endif