1 contributor
75 lines1.9 KB
1#ifndef COR_PLATFORM_H
2#define COR_PLATFORM_H
3// platform specific parts collected together
4#include <stdbool.h>
5#include <stdlib.h>
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// malloc & free...
23static inline void *
24_Cor_Malloc(size_t size){
25 return malloc(size);
26}
27
28static inline void
29_Cor_Free(void *ptr){
30 free(ptr);
31}
32// ...malloc & free
33
34// see CPython again, this time in ctypes.h
35#define COROUTINE_HAVE_ALLOCA_H 1
36
37// Non-reentrant Mutexes
38typedef struct _Cor_Mutex {
39 pthread_mutex_t mut;
40} _Cor_Mutex;
41
42extern void _Cor_Mutex_ctor(_Cor_Mutex *);
43extern void _Cor_Mutex_dtor(_Cor_Mutex *);
44extern void _Cor_Mutex_Lock(_Cor_Mutex *);
45extern void _Cor_Mutex_Unlock(_Cor_Mutex *);
46
47// The 'now' to use for _Cor_Semaphore_Wait, in ns.
48extern int64_t _Cor_Realtime_Now();
49
50typedef struct _Cor_Semaphore {
51 pthread_mutex_t mut;
52 pthread_cond_t cond;
53 unsigned count;
54} _Cor_Semaphore;
55
56extern void _Cor_Semaphore_ctor(_Cor_Semaphore *sem);
57extern void _Cor_Sempahore_dtor(_Cor_Semaphore *sem);
58
59// timeout_when < 0 means 'wait forever'
60// Returns true for success, false for timeout
61extern bool _Cor_Semaphore_Wait(_Cor_Semaphore *sem, int64_t timeout_when);
62
63extern void _Cor_Semaphore_Signal(_Cor_Semaphore *sem);
64
65typedef struct _Cor_Thread {
66 pthread_t th;
67 bool joined;
68} _Cor_Thread;
69
70extern void _Cor_Thread_ctor(_Cor_Thread *, void *(*)(void *), void *);
71extern void _Cor_Thread_dtor(_Cor_Thread *);
72extern void *_Cor_Thread_Join(_Cor_Thread *);
73
74#endif
75