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