60 lines1.6 KB
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
23typedef struct _Cor_Mutex {
24 pthread_mutex_t mut;
25} _Cor_Mutex;
26
27void _Cor_Mutex_ctor(_Cor_Mutex *);
28void _Cor_Mutex_dtor(_Cor_Mutex *);
29void _Cor_Mutex_Lock(_Cor_Mutex *);
30void _Cor_Mutex_Unlock(_Cor_Mutex *);
31
32// The 'now' to use for _Cor_Semaphore_Wait, in ns.
33int64_t _Cor_Realtime_Now();
34
35typedef struct _Cor_Semaphore {
36 pthread_mutex_t mut;
37 pthread_cond_t cond;
38 unsigned count;
39} _Cor_Semaphore;
40
41void _Cor_Semaphore_ctor(_Cor_Semaphore *sem);
42void _Cor_Sempahore_dtor(_Cor_Semaphore *sem);
43
44// timeout_when < 0 means 'wait forever'
45// Returns true for success, false for timeout
46bool _Cor_Semaphore_Wait(_Cor_Semaphore *sem, int64_t timeout_when);
47
48void _Cor_Semaphore_Signal(_Cor_Semaphore *sem);
49
50typedef struct _Cor_Thread {
51 pthread_t th;
52 bool joined;
53} _Cor_Thread;
54
55void _Cor_Thread_ctor(_Cor_Thread *, void *(*)(void *), void *);
56void _Cor_Thread_dtor(_Cor_Thread *);
57void *_Cor_Thread_Join(_Cor_Thread *);
58
59#endif
60