Thread.cxx 1.88 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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.
 */

#include "Thread.hxx"
21
#include "system/Error.hxx"
22

23 24 25 26
#ifdef ANDROID
#include "java/Global.hxx"
#endif

27
void
28
Thread::Start()
29 30 31
{
	assert(!IsDefined());

32
#ifdef _WIN32
33
	handle = ::CreateThread(nullptr, 0, ThreadProc, this, 0, &id);
34 35
	if (handle == nullptr)
		throw MakeLastError("Failed to create thread");
36 37 38
#else
	int e = pthread_create(&handle, nullptr, ThreadProc, this);

39
	if (e != 0)
40
		throw MakeErrno(e, "Failed to create thread");
41 42 43 44
#endif
}

void
45
Thread::Join() noexcept
46 47 48 49
{
	assert(IsDefined());
	assert(!IsInside());

50
#ifdef _WIN32
51 52 53 54 55
	::WaitForSingleObject(handle, INFINITE);
	::CloseHandle(handle);
	handle = nullptr;
#else
	pthread_join(handle, nullptr);
56
	handle = pthread_t();
57 58 59
#endif
}

60
inline void
61
Thread::Run() noexcept
62
{
63
	f();
64 65 66 67 68 69

#ifdef ANDROID
	Java::DetachCurrentThread();
#endif
}

70
#ifdef _WIN32
71 72

DWORD WINAPI
73
Thread::ThreadProc(LPVOID ctx) noexcept
74 75 76
{
	Thread &thread = *(Thread *)ctx;

77
	thread.Run();
78 79 80 81 82 83
	return 0;
}

#else

void *
84
Thread::ThreadProc(void *ctx) noexcept
85 86 87
{
	Thread &thread = *(Thread *)ctx;

88 89 90 91
#ifndef NDEBUG
	thread.inside_handle = pthread_self();
#endif

92
	thread.Run();
93

94 95 96 97
	return nullptr;
}

#endif