IOThread.cxx 2.05 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
 * 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
#include "config.h"
21 22 23
#include "IOThread.hxx"
#include "thread/Mutex.hxx"
#include "thread/Cond.hxx"
24
#include "thread/Thread.hxx"
25
#include "thread/Name.hxx"
26
#include "event/Loop.hxx"
27

28 29
#include <assert.h>

30
static struct {
31 32
	Mutex mutex;
	Cond cond;
33

34
	EventLoop *loop;
35
	Thread thread;
36
} io;
37

38 39
void
io_thread_run(void)
40
{
41
	assert(io_thread_inside());
42
	assert(io.loop != nullptr);
43

44
	io.loop->Run();
45 46
}

47 48
static void
io_thread_func(gcc_unused void *arg)
49
{
50 51
	SetThreadName("io");

52 53
	/* lock+unlock to synchronize with io_thread_start(), to be
	   sure that io.thread is set */
54 55
	io.mutex.lock();
	io.mutex.unlock();
56

57
	io_thread_run();
58 59 60 61 62
}

void
io_thread_init(void)
{
63
	assert(io.loop == nullptr);
64
	assert(!io.thread.IsDefined());
65

66
	io.loop = new EventLoop();
67 68
}

69 70
void
io_thread_start()
71
{
72
	assert(io.loop != nullptr);
73
	assert(!io.thread.IsDefined());
74

75
	const std::lock_guard<Mutex> protect(io.mutex);
76
	io.thread.Start(io_thread_func, nullptr);
77 78
}

79 80 81
void
io_thread_quit(void)
{
82
	assert(io.loop != nullptr);
83

84
	io.loop->Break();
85 86
}

87 88 89
void
io_thread_deinit(void)
{
90
	if (io.thread.IsDefined()) {
91
		io_thread_quit();
92
		io.thread.Join();
93 94
	}

95
	delete io.loop;
96 97
}

98
EventLoop &
99
io_thread_get() noexcept
100
{
101 102 103
	assert(io.loop != nullptr);

	return *io.loop;
104 105
}

106
bool
107
io_thread_inside() noexcept
108
{
109
	return io.thread.IsInside();
110
}