Thread.hxx 2.23 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 20 21 22 23
 * 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_HXX
#define MPD_THREAD_HXX

#include "check.h"
24
#include "util/BindMethod.hxx"
25 26
#include "Compiler.h"

27
#ifdef _WIN32
28 29 30 31 32 33 34 35
#include <windows.h>
#else
#include <pthread.h>
#endif

#include <assert.h>

class Thread {
36 37 38
	typedef BoundMethod<void()> Function;
	const Function f;

39
#ifdef _WIN32
40
	HANDLE handle = nullptr;
41 42
	DWORD id;
#else
43
	pthread_t handle = pthread_t();
44 45 46
#endif

public:
47
	explicit Thread(Function _f) noexcept:f(_f) {}
48 49 50 51

	Thread(const Thread &) = delete;

#ifndef NDEBUG
52
	~Thread() noexcept {
53 54 55 56 57 58
		/* all Thread objects must be destructed manually by calling
		   Join(), to clean up */
		assert(!IsDefined());
	}
#endif

59
	bool IsDefined() const noexcept {
60
#ifdef _WIN32
61 62
		return handle != nullptr;
#else
63
		return handle != pthread_t();
64 65 66 67 68 69 70
#endif
  }

	/**
	 * Check if this thread is the current thread.
	 */
	gcc_pure
71
	bool IsInside() const noexcept {
72
#ifdef _WIN32
73 74
		return GetCurrentThreadId() == id;
#else
75 76 77 78 79 80 81
		/* note: not using pthread_equal() because that
		   function "is undefined if either thread ID is not
		   valid so we can't safely use it on
		   default-constructed values" (comment from
		   libstdc++) - and if both libstdc++ and libc++ get
		   away with this, we can do it as well */
		return pthread_self() == handle;
82 83 84
#endif
	}

85
	void Start();
86
	void Join() noexcept;
87 88

private:
89
	void Run() noexcept;
90

91
#ifdef _WIN32
92
	static DWORD WINAPI ThreadProc(LPVOID ctx) noexcept;
93
#else
94
	static void *ThreadProc(void *ctx) noexcept;
95 96 97 98 99
#endif

};

#endif