mpd/src/thread/Thread.hxx

112 lines
2.5 KiB
C++
Raw Normal View History

/*
2017-01-03 20:48:59 +01:00
* Copyright 2003-2017 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_HXX
#define MPD_THREAD_HXX
#include "check.h"
2017-02-10 22:41:11 +01:00
#include "util/BindMethod.hxx"
2018-08-20 16:19:17 +02:00
#include "util/Compiler.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif
#include <assert.h>
class Thread {
2017-02-10 22:41:11 +01:00
typedef BoundMethod<void()> Function;
const Function f;
#ifdef _WIN32
2016-06-17 19:06:45 +02:00
HANDLE handle = nullptr;
DWORD id;
#else
pthread_t handle = pthread_t();
#ifndef NDEBUG
/**
* This handle is only used by IsInside(), and is set by the
* thread function. Since #handle is set by pthread_create()
* which is racy, we need this attribute for early checks
* inside the thread function.
*/
pthread_t inside_handle = pthread_t();
#endif
#endif
public:
2017-11-26 11:58:53 +01:00
explicit Thread(Function _f) noexcept:f(_f) {}
Thread(const Thread &) = delete;
#ifndef NDEBUG
2017-11-26 11:58:53 +01:00
~Thread() noexcept {
/* all Thread objects must be destructed manually by calling
Join(), to clean up */
assert(!IsDefined());
}
#endif
2017-11-26 11:58:53 +01:00
bool IsDefined() const noexcept {
#ifdef _WIN32
return handle != nullptr;
#else
return handle != pthread_t();
#endif
2018-01-08 09:49:08 +01:00
}
#ifndef NDEBUG
/**
* Check if this thread is the current thread.
*/
gcc_pure
bool IsInside() const noexcept {
#ifdef _WIN32
return GetCurrentThreadId() == id;
#else
/* 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() == inside_handle;
#endif
}
#endif
2017-02-10 22:41:11 +01:00
void Start();
2017-11-26 11:58:53 +01:00
void Join() noexcept;
private:
2017-11-26 11:58:53 +01:00
void Run() noexcept;
2017-02-10 22:43:55 +01:00
#ifdef _WIN32
2017-11-26 11:58:53 +01:00
static DWORD WINAPI ThreadProc(LPVOID ctx) noexcept;
#else
2017-11-26 11:58:53 +01:00
static void *ThreadProc(void *ctx) noexcept;
#endif
};
#endif