all repos — mgba @ daaa2fa5236df5e8976e7e0ba7ac39e0d9233422

mGBA Game Boy Advance Emulator

src/platform/posix/threading.h (view raw)

 1/* Copyright (c) 2013-2015 Jeffrey Pfau
 2 *
 3 * This Source Code Form is subject to the terms of the Mozilla Public
 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 6#ifndef POSIX_THREADING_H
 7#define POSIX_THREADING_H
 8
 9#include "util/common.h"
10
11#include <pthread.h>
12#include <sys/time.h>
13#if defined(__FreeBSD__) || defined(__OpenBSD__)
14#include <pthread_np.h>
15#endif
16
17#define THREAD_ENTRY void*
18typedef THREAD_ENTRY (*ThreadEntry)(void*);
19
20typedef pthread_t Thread;
21typedef pthread_mutex_t Mutex;
22typedef pthread_cond_t Condition;
23
24static inline int MutexInit(Mutex* mutex) {
25	return pthread_mutex_init(mutex, 0);
26}
27
28static inline int MutexDeinit(Mutex* mutex) {
29	return pthread_mutex_destroy(mutex);
30}
31
32static inline int MutexLock(Mutex* mutex) {
33	return pthread_mutex_lock(mutex);
34}
35
36static inline int MutexTryLock(Mutex* mutex) {
37	return pthread_mutex_trylock(mutex);
38}
39
40static inline int MutexUnlock(Mutex* mutex) {
41	return pthread_mutex_unlock(mutex);
42}
43
44static inline int ConditionInit(Condition* cond) {
45	return pthread_cond_init(cond, 0);
46}
47
48static inline int ConditionDeinit(Condition* cond) {
49	return pthread_cond_destroy(cond);
50}
51
52static inline int ConditionWait(Condition* cond, Mutex* mutex) {
53	return pthread_cond_wait(cond, mutex);
54}
55
56static inline int ConditionWaitTimed(Condition* cond, Mutex* mutex, int32_t timeoutMs) {
57	struct timespec ts;
58	struct timeval tv;
59
60	gettimeofday(&tv, 0);
61	ts.tv_sec = tv.tv_sec;
62	ts.tv_nsec = (tv.tv_usec + timeoutMs * 1000L) * 1000L;
63	if (ts.tv_nsec >= 1000000000L) {
64		ts.tv_nsec -= 1000000000L;
65		++ts.tv_sec;
66	}
67
68	return pthread_cond_timedwait(cond, mutex, &ts);
69}
70
71static inline int ConditionWake(Condition* cond) {
72	return pthread_cond_broadcast(cond);
73}
74
75static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
76	return pthread_create(thread, 0, entry, context);
77}
78
79static inline int ThreadJoin(Thread thread) {
80	return pthread_join(thread, 0);
81}
82
83static inline int ThreadSetName(const char* name) {
84#ifdef __APPLE__
85	return pthread_setname_np(name);
86#elif defined(__FreeBSD__) || defined(__OpenBSD__)
87	pthread_set_name_np(pthread_self(), name);
88	return 0;
89#elif !defined(BUILD_PANDORA) // Pandora's glibc is too old
90	return pthread_setname_np(pthread_self(), name);
91#else
92	UNUSED(name);
93	return 0;
94#endif
95}
96
97#endif