Thread.cxx 1.84 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
 * 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 "config.h"
#include "Thread.hxx"
22
#include "system/Error.hxx"
23

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

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

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

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

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

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

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

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

71
#ifdef _WIN32
72 73

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

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

#else

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

89
	thread.Run();
90

91 92 93 94
	return nullptr;
}

#endif