aboutsummaryrefslogtreecommitdiffstats
path: root/src/thread/Util.hxx
blob: 30c2f6200a5f2b84d5cbbbc7266de59214fe894d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * Copyright (C) 2003-2014 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_THREAD_UTIL_HXX
#define MPD_THREAD_UTIL_HXX

#ifdef __linux__
#include <sched.h>
#include <sys/syscall.h>
#include <unistd.h>
#elif defined(WIN32)
#include <windows.h>
#endif

#ifdef __linux__

static int
ioprio_set(int which, int who, int ioprio)
{
	return syscall(__NR_ioprio_set, which, who, ioprio);
}

static void
ioprio_set_idle()
{
	static constexpr int _IOPRIO_WHO_PROCESS = 1;
	static constexpr int _IOPRIO_CLASS_IDLE = 3;
	static constexpr int _IOPRIO_CLASS_SHIFT = 13;
	static constexpr int _IOPRIO_IDLE =
		(_IOPRIO_CLASS_IDLE << _IOPRIO_CLASS_SHIFT) | 7;

	ioprio_set(_IOPRIO_WHO_PROCESS, 0, _IOPRIO_IDLE);
}

#endif

/**
 * Lower the current thread's priority to "idle" (very low).
 */
static inline void
SetThreadIdlePriority()
{
#ifdef __linux__
#ifdef SCHED_IDLE
	static struct sched_param sched_param;
	sched_setscheduler(0, SCHED_IDLE, &sched_param);
#endif

	ioprio_set_idle();

#elif defined(WIN32)
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE);
#endif
};

/**
 * Raise the current thread's priority to "real-time" (very high).
 */
static inline void
SetThreadRealtime()
{
#ifdef __linux__
	struct sched_param sched_param;
	sched_param.sched_priority = 50;

	int policy = SCHED_FIFO;
#ifdef SCHED_RESET_ON_FORK
	policy |= SCHED_RESET_ON_FORK;
#endif

	sched_setscheduler(0, policy, &sched_param);
#endif
};

#endif