src/util/threading.h (view raw)
1#ifndef THREADING_H
2#define THREADING_H
3
4
5#ifdef USE_PTHREADS
6#include <pthread.h>
7
8#define THREAD_ENTRY void*
9typedef THREAD_ENTRY (*ThreadEntry)(void*);
10
11typedef pthread_t Thread;
12typedef pthread_mutex_t Mutex;
13typedef pthread_cond_t Condition;
14
15static inline int MutexInit(Mutex* mutex) {
16 return pthread_mutex_init(mutex, 0);
17}
18
19static inline int MutexDeinit(Mutex* mutex) {
20 return pthread_mutex_destroy(mutex);
21}
22
23static inline int MutexLock(Mutex* mutex) {
24 return pthread_mutex_lock(mutex);
25}
26
27static inline int MutexUnlock(Mutex* mutex) {
28 return pthread_mutex_unlock(mutex);
29}
30
31static inline int ConditionInit(Condition* cond) {
32 return pthread_cond_init(cond, 0);
33}
34
35static inline int ConditionDeinit(Condition* cond) {
36 return pthread_cond_destroy(cond);
37}
38
39static inline int ConditionWait(Condition* cond, Mutex* mutex) {
40 return pthread_cond_wait(cond, mutex);
41}
42
43static inline int ConditionWake(Condition* cond) {
44 return pthread_cond_broadcast(cond);
45}
46
47static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
48 return pthread_create(thread, 0, entry, context);
49}
50
51static inline int ThreadJoin(Thread thread) {
52 return pthread_join(thread, 0);
53}
54
55#else
56#define _WIN32_WINNT 0x0600
57#include <windows.h>
58#define THREAD_ENTRY DWORD WINAPI
59typedef THREAD_ENTRY ThreadEntry(LPVOID);
60
61typedef HANDLE Thread;
62typedef CRITICAL_SECTION Mutex;
63typedef CONDITION_VARIABLE Condition;
64
65static inline int MutexInit(Mutex* mutex) {
66 InitializeCriticalSection(mutex);
67 return GetLastError();
68}
69
70static inline int MutexDeinit(Mutex* mutex) {
71 DeleteCriticalSection(mutex);
72 return GetLastError();
73}
74
75static inline int MutexLock(Mutex* mutex) {
76 EnterCriticalSection(mutex);
77 return GetLastError();
78}
79
80static inline int MutexUnlock(Mutex* mutex) {
81 LeaveCriticalSection(mutex);
82 return GetLastError();
83}
84
85static inline int ConditionInit(Condition* cond) {
86 InitializeConditionVariable(cond);
87 return GetLastError();
88}
89
90static inline int ConditionDeinit(Condition* cond) {
91 // This is a no-op on Windows
92 (void)(cond);
93 return 0;
94}
95
96static inline int ConditionWait(Condition* cond, Mutex* mutex) {
97 SleepConditionVariableCS(cond, mutex, INFINITE);
98 return GetLastError();
99}
100
101static inline int ConditionWake(Condition* cond) {
102 WakeAllConditionVariable(cond);
103 return GetLastError();
104}
105
106static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
107 *thread = CreateThread(NULL, 0, entry, context, 0, 0);
108 return GetLastError();
109}
110
111static inline int ThreadJoin(Thread thread) {
112 DWORD error = WaitForSingleObject(thread, INFINITE);
113 if (error == WAIT_FAILED) {
114 return GetLastError();
115 }
116 return 0;
117}
118#endif
119
120#endif