include/mgba-util/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 <mgba-util/common.h>
10
11CXX_GUARD_START
12
13#include <pthread.h>
14#include <sys/time.h>
15#if defined(__FreeBSD__) || defined(__OpenBSD__)
16#include <pthread_np.h>
17#endif
18
19#define THREAD_ENTRY void*
20typedef THREAD_ENTRY (*ThreadEntry)(void*);
21
22typedef pthread_t Thread;
23typedef pthread_mutex_t Mutex;
24typedef pthread_cond_t Condition;
25
26static inline int MutexInit(Mutex* mutex) {
27 return pthread_mutex_init(mutex, 0);
28}
29
30static inline int MutexDeinit(Mutex* mutex) {
31 return pthread_mutex_destroy(mutex);
32}
33
34static inline int MutexLock(Mutex* mutex) {
35 return pthread_mutex_lock(mutex);
36}
37
38static inline int MutexTryLock(Mutex* mutex) {
39 return pthread_mutex_trylock(mutex);
40}
41
42static inline int MutexUnlock(Mutex* mutex) {
43 return pthread_mutex_unlock(mutex);
44}
45
46static inline int ConditionInit(Condition* cond) {
47 return pthread_cond_init(cond, 0);
48}
49
50static inline int ConditionDeinit(Condition* cond) {
51 return pthread_cond_destroy(cond);
52}
53
54static inline int ConditionWait(Condition* cond, Mutex* mutex) {
55 return pthread_cond_wait(cond, mutex);
56}
57
58static inline int ConditionWaitTimed(Condition* cond, Mutex* mutex, int32_t timeoutMs) {
59 struct timespec ts;
60 struct timeval tv;
61
62 gettimeofday(&tv, 0);
63 ts.tv_sec = tv.tv_sec;
64 ts.tv_nsec = (tv.tv_usec + timeoutMs * 1000L) * 1000L;
65 if (ts.tv_nsec >= 1000000000L) {
66 ts.tv_nsec -= 1000000000L;
67 ++ts.tv_sec;
68 }
69
70 return pthread_cond_timedwait(cond, mutex, &ts);
71}
72
73static inline int ConditionWake(Condition* cond) {
74 return pthread_cond_broadcast(cond);
75}
76
77static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
78 return pthread_create(thread, 0, entry, context);
79}
80
81static inline int ThreadJoin(Thread thread) {
82 return pthread_join(thread, 0);
83}
84
85static inline int ThreadSetName(const char* name) {
86#ifdef __APPLE__
87 return pthread_setname_np(name);
88#elif defined(__FreeBSD__) || defined(__OpenBSD__)
89 pthread_set_name_np(pthread_self(), name);
90 return 0;
91#elif !defined(BUILD_PANDORA) // Pandora's glibc is too old
92 return pthread_setname_np(pthread_self(), name);
93#else
94 UNUSED(name);
95 return 0;
96#endif
97}
98
99CXX_GUARD_END
100
101#endif