Raw
1 /*
2 * Header used to adapt pthread-based POSIX code to Windows API threads.
3 *
4 * Copyright (C) 2009 Andrzej K. Haczewski <ahaczewski@gmail.com>
5 */
6
7 #ifndef PTHREAD_H
8 #define PTHREAD_H
9
10 #ifndef WIN32_LEAN_AND_MEAN
11 #define WIN32_LEAN_AND_MEAN
12 #endif
13
14 #include <windows.h>
15
16 /*
17 * Defines that adapt Windows API threads to pthreads API
18 */
19 #define pthread_mutex_t CRITICAL_SECTION
20
21 static inline int return_0(int i UNUSED) {
22 return 0;
23 }
24 #define pthread_mutex_init(a,b) return_0((InitializeCriticalSection((a)), 0))
25 #define pthread_mutex_destroy(a) DeleteCriticalSection((a))
26 #define pthread_mutex_lock EnterCriticalSection
27 #define pthread_mutex_unlock LeaveCriticalSection
28
29 typedef int pthread_mutexattr_t;
30 #define pthread_mutexattr_init(a) (*(a) = 0)
31 #define pthread_mutexattr_destroy(a) do {} while (0)
32 #define pthread_mutexattr_settype(a, t) 0
33 #define PTHREAD_MUTEX_RECURSIVE 0
34
35 #define pthread_cond_t CONDITION_VARIABLE
36
37 #define pthread_cond_init(a,b) return_0((InitializeConditionVariable((a)), 0))
38 #define pthread_cond_destroy(a) do {} while (0)
39 #define pthread_cond_signal WakeConditionVariable
40 #define pthread_cond_broadcast WakeAllConditionVariable
41
42 /*
43 * Simple thread creation implementation using pthread API
44 */
45 typedef struct {
46 HANDLE handle;
47 void *(*start_routine)(void*);
48 void *arg;
49 DWORD tid;
50 } pthread_t;
51
52 int pthread_create(pthread_t *thread, const void *unused,
53 void *(*start_routine)(void*), void *arg);
54
55 /*
56 * To avoid the need of copying a struct, we use small macro wrapper to pass
57 * pointer to win32_pthread_join instead.
58 */
59 #define pthread_join(a, b) win32_pthread_join(&(a), (b))
60
61 int win32_pthread_join(pthread_t *thread, void **value_ptr);
62
63 #define pthread_equal(t1, t2) ((t1).tid == (t2).tid)
64 pthread_t pthread_self(void);
65
66 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
67 int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
68 const struct timespec *abstime);
69
70 static inline void NORETURN pthread_exit(void *ret)
71 {
72 _endthreadex((unsigned)(uintptr_t)ret);
73 }
74
75 typedef DWORD pthread_key_t;
76 static inline int pthread_key_create(pthread_key_t *keyp, void (*destructor)(void *value) UNUSED)
77 {
78 return (*keyp = TlsAlloc()) == TLS_OUT_OF_INDEXES ? EAGAIN : 0;
79 }
80
81 static inline int pthread_key_delete(pthread_key_t key)
82 {
83 return TlsFree(key) ? 0 : EINVAL;
84 }
85
86 static inline int pthread_setspecific(pthread_key_t key, const void *value)
87 {
88 return TlsSetValue(key, (void *)value) ? 0 : EINVAL;
89 }
90
91 static inline void *pthread_getspecific(pthread_key_t key)
92 {
93 return TlsGetValue(key);
94 }
95
96 #ifndef __MINGW64_VERSION_MAJOR
97 static inline int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
98 {
99 return 0;
100 }
101 #endif
102
103 #endif /* PTHREAD_H */