mpd/src/thread/Thread.hxx

101 lines
1.9 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright The Music Player Daemon Project
#ifndef MPD_THREAD_HXX
#define MPD_THREAD_HXX
2017-02-10 22:41:11 +01:00
#include "util/BindMethod.hxx"
#include <cassert>
#ifdef _WIN32
#include <processthreadsapi.h>
#else
#include <pthread.h>
#endif
class Thread {
typedef BoundMethod<void() noexcept> Function;
2017-02-10 22:41:11 +01:00
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;
2018-09-21 16:54:42 +02:00
Thread &operator=(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.
*/
2021-10-13 11:28:04 +02:00
[[gnu::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
/**
* Start the thread.
*
* Throws on error.
*/
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