DeferredMonitor.hxx 2.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright (C) 2003-2013 The Music Player Daemon Project
 * 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_SOCKET_DEFERRED_MONITOR_HXX
#define MPD_SOCKET_DEFERRED_MONITOR_HXX

#include "check.h"
24
#include "Compiler.h"
25

26
#ifdef USE_INTERNAL_EVENTLOOP
27 28
#include "SocketMonitor.hxx"
#include "WakeFD.hxx"
29 30 31
#endif

#ifdef USE_GLIB_EVENTLOOP
32
#include <glib.h>
33
#endif
34 35 36

#include <atomic>

37 38
class EventLoop;

39 40 41
/**
 * Defer execution of an event into an #EventLoop.
 */
42
class DeferredMonitor
43
#ifdef USE_INTERNAL_EVENTLOOP
44 45 46
	: private SocketMonitor
#endif
{
47
#ifdef USE_INTERNAL_EVENTLOOP
48 49
	std::atomic_bool pending;
	WakeFD fd;
50
#endif
51

52 53
#ifdef USE_GLIB_EVENTLOOP
	EventLoop &loop;
54
	std::atomic<guint> source_id;
55
#endif
56 57

public:
58
#ifdef USE_INTERNAL_EVENTLOOP
59 60 61 62 63
	DeferredMonitor(EventLoop &_loop)
		:SocketMonitor(_loop), pending(false) {
		SocketMonitor::Open(fd.Get());
		SocketMonitor::Schedule(SocketMonitor::READ);
	}
64 65 66
#endif

#ifdef USE_GLIB_EVENTLOOP
67 68
	DeferredMonitor(EventLoop &_loop)
		:loop(_loop), source_id(0) {}
69
#endif
70 71

	~DeferredMonitor() {
72
#ifdef USE_INTERNAL_EVENTLOOP
73 74
		/* avoid closing the WakeFD twice */
		SocketMonitor::Steal();
75 76 77
#endif

#ifdef USE_GLIB_EVENTLOOP
78
		Cancel();
79
#endif
80 81
	}

82
	EventLoop &GetEventLoop() {
83
#ifdef USE_INTERNAL_EVENTLOOP
84
		return SocketMonitor::GetEventLoop();
85 86 87
#endif

#ifdef USE_GLIB_EVENTLOOP
88
		return loop;
89
#endif
90 91
	}

92 93 94 95
	void Schedule();
	void Cancel();

protected:
96
	virtual void RunDeferred() = 0;
97 98

private:
99
#ifdef USE_INTERNAL_EVENTLOOP
100
	virtual bool OnSocketReady(unsigned flags) override final;
101 102 103
#endif

#ifdef USE_GLIB_EVENTLOOP
104
	void Run();
105
	static gboolean Callback(gpointer data);
106
#endif
107 108 109
};

#endif /* MAIN_NOTIFY_H */