IOThread.cxx 2.13 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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
#include "system/FatalError.hxx"
28
#include "util/Error.hxx"
29

30 31
#include <assert.h>

32
static struct {
33 34
	Mutex mutex;
	Cond cond;
35

36
	EventLoop *loop;
37
	Thread thread;
38
} io;
39

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

46
	io.loop->Run();
47 48
}

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

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

59
	io_thread_run();
60 61 62 63 64
}

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

68
	io.loop = new EventLoop();
69 70
}

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

77 78
	const ScopeLock protect(io.mutex);

79 80
	Error error;
	if (!io.thread.Start(io_thread_func, nullptr, error))
81
		FatalError(error);
82 83
}

84 85 86
void
io_thread_quit(void)
{
87
	assert(io.loop != nullptr);
88

89
	io.loop->Break();
90 91
}

92 93 94
void
io_thread_deinit(void)
{
95
	if (io.thread.IsDefined()) {
96
		io_thread_quit();
97
		io.thread.Join();
98 99
	}

100
	delete io.loop;
101 102
}

103 104
EventLoop &
io_thread_get()
105
{
106 107 108
	assert(io.loop != nullptr);

	return *io.loop;
109 110
}

111 112 113
bool
io_thread_inside(void)
{
114
	return io.thread.IsInside();
115
}