| 1 | #ifndef COR_PLATFORM_H |
| 2 | #define COR_PLATFORM_H |
| 3 | // platform specific parts collected together |
| 4 | #include <stdbool.h> |
| 5 | |
| 6 | #include <pthread.h> |
| 7 | #include <errno.h> |
| 8 | |
| 9 | // inspired by CPython to achieve platform indenpendence for thread local variables |
| 10 | #ifdef thread_local |
| 11 | #define _Cor_thread_local thread_local |
| 12 | #elif __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) |
| 13 | #define _Cor_thread_local _Thread_local |
| 14 | #elif defined(_MSC_VER) /* AKA NT_THREADS */ |
| 15 | #define _Cor_thread_local __declspec(thread) |
| 16 | #elif defined(__GNUC__) /* includes clang */ |
| 17 | #define _Cor_thread_local __thread |
| 18 | #else |
| 19 | #define _Cor_thread_local |
| 20 | #endif |
| 21 | |
| 22 | // Non-reentrant Mutexes |
| 23 | typedef struct _Cor_Mutex { |
| 24 | pthread_mutex_t mut; |
| 25 | } _Cor_Mutex; |
| 26 | |
| 27 | void _Cor_Mutex_ctor(_Cor_Mutex *); |
| 28 | void _Cor_Mutex_dtor(_Cor_Mutex *); |
| 29 | void _Cor_Mutex_Lock(_Cor_Mutex *); |
| 30 | void _Cor_Mutex_Unlock(_Cor_Mutex *); |
| 31 | |
| 32 | // The 'now' to use for _Cor_Semaphore_Wait, in ns. |
| 33 | int64_t _Cor_Realtime_Now(); |
| 34 | |
| 35 | typedef struct _Cor_Semaphore { |
| 36 | pthread_mutex_t mut; |
| 37 | pthread_cond_t cond; |
| 38 | unsigned count; |
| 39 | } _Cor_Semaphore; |
| 40 | |
| 41 | void _Cor_Semaphore_ctor(_Cor_Semaphore *sem); |
| 42 | void _Cor_Sempahore_dtor(_Cor_Semaphore *sem); |
| 43 | |
| 44 | // timeout_when < 0 means 'wait forever' |
| 45 | // Returns true for success, false for timeout |
| 46 | bool _Cor_Semaphore_Wait(_Cor_Semaphore *sem, int64_t timeout_when); |
| 47 | |
| 48 | void _Cor_Semaphore_Signal(_Cor_Semaphore *sem); |
| 49 | |
| 50 | #endif |
| 51 | |