Introducing the Big Tinc Lock.
[tinc] / src / threads.h
1 #ifndef __THREADS_H__
2 #define __THREADS_H__
3
4 #ifdef HAVE_MINGW
5 typedef HANDLE thread_t;
6 typedef CRITICAL_SECTION mutex_t;
7
8 static inline bool thread_create(thread_t *tid, void (*func)(void *), void *arg) {
9         *tid = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, arg, 0, NULL);
10         return tid;
11 }
12 static inline void thread_destroy(thread_t *tid) {
13         WaitForSingleObject(tid, 0);
14         CloseHandle(tid);
15 }
16 static inline void mutex_create(mutex_t *mutex) {
17         InitializeCriticalSection(mutex);
18 }
19 static inline void mutex_lock(mutex_t *mutex) {
20         EnterCriticalSection(mutex);
21 }
22 static inline void mutex_unlock(mutex_t *mutex) {
23         LeaveCriticalSection(mutex);
24 }
25 #else
26 #include <pthread.h>
27
28 typedef pthread_t thread_t;
29 typedef pthread_mutex_t mutex_t;
30
31 static inline bool thread_create(thread_t *tid, void (*func)(void *), void *arg) {
32         return !pthread_create(tid, NULL, (void *(*)(void *))func, arg);
33 }
34 static inline void thread_destroy(thread_t *tid) {
35         pthread_cancel(*tid);
36         pthread_join(*tid, NULL);
37 }
38 static inline void mutex_create(mutex_t *mutex) {
39         pthread_mutex_init(mutex, NULL);
40 }
41 #if 1
42 #define mutex_lock(m) logger(LOG_DEBUG, "mutex_lock() at " __FILE__ " line %d", __LINE__); pthread_mutex_lock(m)
43 #define mutex_unlock(m) logger(LOG_DEBUG, "mutex_unlock() at " __FILE__ " line %d", __LINE__); pthread_mutex_unlock(m)
44 #else
45 static inline void mutex_lock(mutex_t *mutex) {
46         pthread_mutex_lock(mutex);
47 }
48 static inline void mutex_unlock(mutex_t *mutex) {
49         pthread_mutex_unlock(mutex);
50 }
51 #endif
52 #endif
53
54 #endif