| 1 | /** |
| 2 | * Copyright (C) 2011-2012 Juho Vähä-Herttua |
| 3 | * |
| 4 | * This library is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU Lesser General Public |
| 6 | * License as published by the Free Software Foundation; either |
| 7 | * version 2.1 of the License, or (at your option) any later version. |
| 8 | * |
| 9 | * This library is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | * Lesser General Public License for more details. |
| 13 | */ |
| 14 | |
| 15 | #ifndef THREADS_H |
| 16 | #define THREADS_H |
| 17 | |
| 18 | #if defined(WIN32) |
| 19 | #include <windows.h> |
| 20 | |
| 21 | #define sleepms(x) Sleep(x) |
| 22 | |
| 23 | typedef HANDLE thread_handle_t; |
| 24 | |
| 25 | #define THREAD_RETVAL DWORD WINAPI |
| 26 | #define THREAD_CREATE(handle, func, arg) \ |
| 27 | handle = CreateThread(NULL, 0, func, arg, 0, NULL) |
| 28 | #define THREAD_JOIN(handle) do { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } while(0) |
| 29 | |
| 30 | typedef HANDLE mutex_handle_t; |
| 31 | |
| 32 | #define MUTEX_CREATE(handle) handle = CreateMutex(NULL, FALSE, NULL) |
| 33 | #define MUTEX_LOCK(handle) WaitForSingleObject(handle, INFINITE) |
| 34 | #define MUTEX_UNLOCK(handle) ReleaseMutex(handle) |
| 35 | #define MUTEX_DESTROY(handle) CloseHandle(handle) |
| 36 | |
| 37 | #else /* Use pthread library */ |
| 38 | |
| 39 | #include <pthread.h> |
| 40 | #include <unistd.h> |
| 41 | |
| 42 | #define sleepms(x) usleep((x)*1000) |
| 43 | |
| 44 | typedef pthread_t thread_handle_t; |
| 45 | |
| 46 | #define THREAD_RETVAL void * |
| 47 | #define THREAD_CREATE(handle, func, arg) \ |
| 48 | if (pthread_create(&(handle), NULL, func, arg)) handle = 0 |
| 49 | #define THREAD_JOIN(handle) pthread_join(handle, NULL) |
| 50 | |
| 51 | typedef pthread_mutex_t mutex_handle_t; |
| 52 | |
| 53 | #define MUTEX_CREATE(handle) pthread_mutex_init(&(handle), NULL) |
| 54 | #define MUTEX_LOCK(handle) pthread_mutex_lock(&(handle)) |
| 55 | #define MUTEX_UNLOCK(handle) pthread_mutex_unlock(&(handle)) |
| 56 | #define MUTEX_DESTROY(handle) pthread_mutex_destroy(&(handle)) |
| 57 | |
| 58 | #endif |
| 59 | |
| 60 | #endif /* THREADS_H */ |