threads.h 2.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
#ifndef _THREADS_H_
#define _THREADS_H_


#include "common.h"


#ifdef MINGW

#include <windows.h>

#define thread_t HANDLE
#define mutex_t HANDLE

//

static inline void
thread_create (thread_t * thread, void * (* thread_fn) (void *), void * data) {
	*thread = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) thread_fn, data, 0, NULL);
	check_win_error (*thread == NULL, "failed to create thread");
}


static inline void
mutex_init (mutex_t * mutex) {
	*mutex = CreateMutex (NULL, FALSE, NULL);
	check_win_error (*mutex == NULL, "failed to create mutex");
}


static inline void
mutex_lock (mutex_t * mutex) {
	DWORD result = WaitForSingleObject (*mutex, INFINITE);
	check_win_error (result != WAIT_OBJECT_0, "failed to lock mutex");
}


static inline void
mutex_unlock (mutex_t * mutex) {
	BOOL released = ReleaseMutex (*mutex);
	check_win_error (!released, "failed to release mutex");
}


static inline void
mutex_destroy (mutex_t * mutex) {
	BOOL closed = CloseHandle (*mutex);
	check_win_error (!closed, "failed to destroy mutex");
}


#else

#include <pthread.h>

#define thread_t pthread_t
#define mutex_t pthread_mutex_t

//

static inline void
thread_create (thread_t * thread, void * (* thread_fn) (void *), void * data) {
	int result = pthread_create (thread, NULL, thread_fn, data);
	check_std_error (result != 0, "failed to create thread");
}


static inline void
thread_join (thread_t * thread) {
	int result = pthread_join (*thread, NULL);
	check_std_error (result != 0, "failed to join thread");
}



static inline void
mutex_init (mutex_t * mutex) {
	int result = pthread_mutex_init (mutex, NULL);
	check_std_error (result != 0, "failed to initialize mutex");
}


static inline void
mutex_lock (mutex_t * mutex) {
	int result = pthread_mutex_lock (mutex);
	check_std_error (result != 0, "failed to lock mutex");
}


static inline void
mutex_unlock (mutex_t * mutex) {
	int result = pthread_mutex_unlock (mutex);
	check_std_error (result != 0, "failed to release mutex");
}


static inline void
mutex_destroy (mutex_t * mutex) {
	int result = pthread_mutex_destroy (mutex);
	check_std_error (result != 0, "failed to destroy mutex");
}

#endif /* !MINGW */

#endif /* _THREADS_H_ */