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