coroutine.h
Go to the documentation of this file.
1 
55 #ifndef COROUTINE_H
56 #define COROUTINE_H
57 
58 typedef void * co_t;
59 typedef unsigned int semaphore_t;
60 
61 enum {
62  CO_READY,
63  CO_WAIT,
64  CO_YIELD,
65  CO_END,
66  CO_SKIP,
67 };
68 
73 #define CORO_CONTEXT( name ) \
74  co_t co_##name
75 
76 #define CORO_CONTEXT_INIT( name ) ({ \
77  co_##name = NULL; \
78 })
79 
83 #define CORO_LOCAL static
84 
89 #define CORO_DEFINE( name ) \
90  int coro_##name( co_t *co_p )
91 
96 #define CORO_BEGIN( initial ) ({ \
97  initial; \
98  if ( *co_p ) goto **co_p; \
99 })
100 
106 #define CORO_END( final ) ({ \
107  __label__ L; \
108  *co_p = &&L; \
109 L: \
110  final; \
111  return CO_END; \
112 })
113 
118 #define CORO_YIELD( final ) ({ \
119  __label__ L; \
120  *co_p = &&L; \
121  final; \
122  return CO_YIELD; \
123 L:; \
124 })
125 
131 #define CORO_WAIT( cond, ... ) ({ \
132  __label__ L; \
133  *co_p = &&L; \
134 L: \
135  if (!( cond )) { \
136  __VA_ARGS__; /* final */ \
137  return CO_WAIT; \
138  } \
139 })
140 
145 #define CORO_RESTART( final ) ({ \
146  *co_p = NULL; \
147  final; \
148  return CO_YIELD; \
149 })
150 
155 #define CORO_QUIT( final ) CORO_END( final )
156 
161 #define CORO_CALL( name ) \
162  coro_##name( &co_##name )
163 
169 #define CORO_ALIVE( coro ) (( coro ) < CO_END )
170 
176 #define CORO_WAIT_CORO( coro, ... ) \
177  CORO_WAIT( !CORO_ALIVE( coro ), ## __VA_ARGS__ )
178 
184 #define SEMAPHORE_INIT( name, val ) ({ \
185  name = val; \
186 })
187 
193 #define SEMAPHORE_ACQUIRE( name, ... ) ({ \
194  CORO_WAIT(( name > 0 ), ## __VA_ARGS__ ); \
195  --name; \
196 })
197 
202 #define SEMAPHORE_RELEASE( name ) ({ \
203  ++name; \
204 })
205 
206 #endif /* COROUTINE_H */
207