DeferredMonitor.hxx 2.09 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 27 28 29
#ifdef USE_EPOLL
#include "SocketMonitor.hxx"
#include "WakeFD.hxx"
#else
30
#include "thread/Mutex.hxx"
31
#include <glib.h>
32
#endif
33 34 35

#include <atomic>

36 37
class EventLoop;

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

52 53 54
	Mutex mutex;

	guint source_id;
55
#endif
56 57

public:
58 59 60 61 62 63 64
#ifdef USE_EPOLL
	DeferredMonitor(EventLoop &_loop)
		:SocketMonitor(_loop), pending(false) {
		SocketMonitor::Open(fd.Get());
		SocketMonitor::Schedule(SocketMonitor::READ);
	}
#else
65 66
	DeferredMonitor(EventLoop &_loop)
		:loop(_loop), source_id(0) {}
67
#endif
68 69

	~DeferredMonitor() {
70 71 72 73
#ifdef USE_EPOLL
		/* avoid closing the WakeFD twice */
		SocketMonitor::Steal();
#else
74
		Cancel();
75
#endif
76 77
	}

78
	EventLoop &GetEventLoop() {
79 80 81
#ifdef USE_EPOLL
		return SocketMonitor::GetEventLoop();
#else
82
		return loop;
83
#endif
84 85
	}

86 87 88 89
	void Schedule();
	void Cancel();

protected:
90
	virtual void RunDeferred() = 0;
91 92

private:
93 94 95
#ifdef USE_EPOLL
	virtual bool OnSocketReady(unsigned flags) override final;
#else
96
	void Run();
97
	static gboolean Callback(gpointer data);
98
#endif
99 100 101
};

#endif /* MAIN_NOTIFY_H */