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