0 branches 0 tags
10 11
12
13 14
Thread security added
on 9:25 AM Sep 2 2025
trunk/coroutine/coroutine.c
11
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#include "coroutine.h"
#include <assert.h>
#include <setjmp.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define COROUTINE_STACK_SIZE 16384
#define COROUTINE_STARTUP_STACK_SIZE 1024
static void *mustmalloc(size_t size){
void *p = malloc(size);
assert(p);
return p;
}
#define New(type, ...) (type##_ctor((type *)mustmalloc(sizeof(type), ## __VA_ARGS__)))
#define Delete(ptr, type) ((ptr) ? (type##_dtor(ptr), free(ptr), (ptr) = NULL) : (void)0)
///////////////////////////////////////////////////////////////////////////////
// Semaphore built from mutex & condition variables...
//
// Using pthread.h (more widely available than the C standard library thread.h)
///////////////////////////////////////////////////////////////////////////////
typedef struct Semaphore {
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} Semaphore;
static void Semaphore_ctor(Semaphore *sem, int initial_count){
sem->count = initial_count;
int r = pthread_mutex_init(&sem->mutex, NULL);
assert(r == 0);
r = pthread_cond_init(&sem->cond, NULL);
assert(r == 0);
}
static void Semaphore_dtor(Semaphore *sem){
int r = pthread_mutex_destroy(&sem->mutex);
assert(r == 0);
r = pthread_cond_destroy(&sem->cond);
assert(r == 0);
}
static void Semaphore_Claim(Semaphore *sem){
int r = pthread_mutex_lock(&sem->mutex);
assert(r == 0);
while (sem->count <= 0) {
r = pthread_cond_wait(&sem->cond, &sem->mutex);
assert(r == 0);
}
sem->count--;
r = pthread_mutex_unlock(&sem->mutex);
assert(r == 0);
}
static void Semaphore_Release(Semaphore *sem){
int r = pthread_mutex_lock(&sem->mutex);
assert(r == 0);
sem->count++;
r = pthread_cond_broadcast(&sem->cond);
assert(r == 0);
r = pthread_mutex_unlock(&sem->mutex);
assert(r == 0);
}
///////////////////////////////////////////////////////////////////////////////
// ...semaphore built from mutex
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// 2-way linked lists...
//
// Brought inline here to avoid namespace polution
///////////////////////////////////////////////////////////////////////////////
typedef struct List_Link List_Link;
struct List_Link {
List_Link *next;
List_Link *prev;
};
typedef struct List_Head List_Head;
struct List_Head {
union {
struct {
List_Link link;
List_Link *filler;
} fwd;
struct {
List_Link *filler;
List_Link link;
} back;
};
};
static inline bool List_IsEmpty(const List_Head *list) {
return list->fwd.link.next == &list->back.link;
}
static inline List_Link *List_GetHead(const List_Head *list) {
return List_IsEmpty(list) ? NULL : list->fwd.link.next;
}
static inline List_Link *List_GetTail(const List_Head *list) {
return List_IsEmpty(list) ? NULL : list->back.link.prev;
}
#define OFFSETOF(Container, Field) ((char *)&((Container *)4)->Field - (char *)(Container *)4)
#define List_Link_Container(Container, Link, link) ((Container *)((char *)(link) - OFFSETOF(Container, Link)))
static inline void List_Init(List_Head *list)
{
list->fwd.link.next = &list->back.link;
list->fwd.link.prev = NULL;
list->back.link.prev = &list->fwd.link;
}
static inline void List_AddHead(List_Head *list, List_Link *link)
{
List_Link *first = list->fwd.link.next;
link->next = first;
link->prev = &list->fwd.link;
first->prev = link;
list->fwd.link.next = link;
}
static inline void List_AddTail(List_Head *list, List_Link *link)
{
List_Link *last = list->back.link.prev;
link->prev = last;
link->next = &list->back.link;
last->next = link;
list->back.link.prev = link;
}
static inline void List_Remove(List_Link *link)
{
link->prev->next = link->next;
link->next->prev = link->prev;
}
///////////////////////////////////////////////////////////////////////////////
// ...2-way linked lists
///////////////////////////////////////////////////////////////////////////////
enum {
Coroutines_Idle,
Coroutines_Starting,
Coroutines_Started,
Coroutines_Active,
Coroutines_Stopping
};
enum {
Chunk_Initial,
Chunk_Create,
Chunk_Enter
};
enum {
Coroutine_Constructing,
Coroutine_Free,
Coroutine_Idle,
Coroutine_Running,
Coroutine_Waiting,
Coroutine_Complete
};
enum {
Coroutines_Init,
Coroutines_AllocatedChunk,
Coroutines_CoroutineComplete,
};
struct Coroutine {
List_Link link;
jmp_buf buf;
void *this;
Coroutine_YieldCallback on_yield;
Coroutine_Start start;
void *entry_param;
void *value;
char state;
char action;
};
typedef struct Coroutines Coroutines;
struct Coroutines {
pthread_mutex_t mutex;
jmp_buf controller;
jmp_buf chunk_allocated;
// singletons
Coroutine *tip; // top of stack chunk
Coroutine *active; // currently running coroutine
Coroutine *primary; // Coroutine_Run coroutine
// lists
List_Head free;
List_Head inactive; // idle or complete
List_Head runable; // running or waiting to run
List_Head waiting; // yielded / waiting to run
Semaphore waiting_sem;
// state
char state;
};
Coroutines g_c;
static void stack_chunk_chunk(Coroutine *parent);
static void stack_chunk_base(Coroutine *parent);
static void Coroutine_PrimeStackChunks()
{
unsigned char chunk_of_stack[COROUTINE_STACK_SIZE];
chunk_of_stack[0] = 0xde;
chunk_of_stack[1] = 0xad;
chunk_of_stack[2] = 0xbe;
chunk_of_stack[3] = 0xef;
chunk_of_stack[COROUTINE_STACK_SIZE - 4] = 0xde;
chunk_of_stack[COROUTINE_STACK_SIZE - 3] = 0xad;
chunk_of_stack[COROUTINE_STACK_SIZE - 2] = 0xbe;
chunk_of_stack[COROUTINE_STACK_SIZE - 1] = 0xef;
stack_chunk_base(NULL);
}
static void stack_chunk_chunk(Coroutine *parent){
unsigned char chunk_of_stack[COROUTINE_STACK_SIZE];
chunk_of_stack[0] = 0xde;
chunk_of_stack[1] = 0xad;
chunk_of_stack[2] = 0xbe;
chunk_of_stack[3] = 0xef;
chunk_of_stack[COROUTINE_STACK_SIZE - 4] = 0xde;
chunk_of_stack[COROUTINE_STACK_SIZE - 3] = 0xad;
chunk_of_stack[COROUTINE_STACK_SIZE - 2] = 0xbe;
chunk_of_stack[COROUTINE_STACK_SIZE - 1] = 0xef;
stack_chunk_base(parent);
}
static void Coroutine_RunNext()
{
// arrvie here with mutex unlocked
Semaphore_Claim(&g_c.waiting_sem);
int r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
assert(!List_IsEmpty(&g_c.runable));
Coroutine *next = List_Link_Container(Coroutine, link, List_GetHead(&g_c.runable));
assert(next->state == Coroutine_Running);
longjmp(next->buf, Chunk_Enter);
assert(false);
}
static void stack_chunk_base(Coroutine *parent){
Coroutine here;
here.state = Coroutine_Constructing;
switch (setjmp(here.buf)) {
case Chunk_Initial:
// got here for the first time
// parent now has a chunk_of_stack - add it to the free list
if (parent) {
assert(parent->state == Coroutine_Constructing);
parent->state = Coroutine_Free;
List_AddHead(&g_c.free, &parent->link);
}
// note that here is the tip of the chunk-claim stack
g_c.tip = &here;
// return to the coroutine allocator
longjmp(g_c.chunk_allocated, 1);
case Chunk_Create:
// request to create a new chunk on the stack
assert(here.state == Coroutine_Constructing);
stack_chunk_chunk(&here);
assert(false);
case Chunk_Enter:
// request to start a coroutine (ie use the chunk for a coroutine)
// arrive here with mutex locked
assert(here.state == Coroutine_Running);
g_c.active = &here;
int r = pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
here.value = here.start(here.entry_param);
r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
g_c.active = NULL;
assert(here.state == Coroutine_Running);
List_Remove(&here.link);
here.state = Coroutine_Complete;
List_AddTail(&g_c.inactive, &here.link);
// coroutine has completed
if (g_c.primary == &here) {
// if primary coroutine - return to Coroutine_Run
longjmp(g_c.controller, Coroutines_CoroutineComplete);
}
r = pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
Coroutine_RunNext();
assert(false);
}
}
void Coroutine_StartSystem()
{
assert(g_c.state == Coroutines_Idle);
pthread_mutexattr_t attr;
int r = pthread_mutexattr_init(&attr);
assert(r == 0);
r = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
assert(r == 0);
r = pthread_mutex_init(&g_c.mutex, &attr);
assert(r == 0);
r = pthread_mutexattr_destroy(&attr);
assert(r == 0);
g_c.state = Coroutines_Starting;
g_c.tip = NULL;
g_c.active = NULL;
List_Init(&g_c.free);
List_Init(&g_c.inactive);
List_Init(&g_c.runable);
List_Init(&g_c.waiting);
Semaphore_ctor(&g_c.waiting_sem, 0);
// prime the chunk system
if (!setjmp(g_c.chunk_allocated)){
Coroutine_PrimeStackChunks();
assert(false);
}
assert(g_c.state == Coroutines_Starting);
g_c.state = Coroutines_Started;
}
void Coroutine_StopSystem()
{
int r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
assert(g_c.state == Coroutines_Started);
g_c.state = Coroutines_Stopping;
assert(List_IsEmpty(&g_c.inactive));
Semaphore_dtor(&g_c.waiting_sem);
assert(g_c.state == Coroutines_Stopping);
pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
g_c.state = Coroutines_Idle;
r = pthread_mutex_destroy(&g_c.mutex);
assert(r == 0);
}
void *Coroutine_Run(Coroutine *cor, void *value){
int r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
assert(g_c.state == Coroutines_Started);
g_c.state = Coroutines_Active;
g_c.primary = cor;
Coroutine_Continue(g_c.primary, value, true);
if (!setjmp(g_c.controller)){
pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
// start the first coroutine
Coroutine_RunNext();
}
// arrive here with mutex locked
assert(List_IsEmpty(&g_c.runable));
assert(List_IsEmpty(&g_c.waiting));
assert(g_c.state == Coroutines_Active);
g_c.state = Coroutines_Started;
pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
return Coroutine_GetValue(cor);
}
Coroutine *Coroutine_New(void *this, Coroutine_YieldCallback on_yield, Coroutine_Start start){
assert(g_c.state == Coroutines_Started || g_c.state == Coroutines_Active);
// if none free - add one
if (List_IsEmpty(&g_c.free)){
if (!setjmp(g_c.chunk_allocated)){
longjmp(g_c.tip->buf, Chunk_Create);
}
}
Coroutine *cor = List_Link_Container(Coroutine, link, List_GetHead(&g_c.free));
assert(cor->state == Coroutine_Free);
cor->state = Coroutine_Idle;
cor->this = this;
cor->start = start;
cor->on_yield = on_yield;
cor->value = NULL;
List_Remove(&cor->link);
List_AddHead(&g_c.inactive, &cor->link);
return cor;
}
void Coroutine_Delete(Coroutine *cor){
assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Complete);
cor->state = Coroutine_Free;
List_Remove(&cor->link);
List_AddTail(&g_c.free, &cor->link);
}
void Coroutine_Continue(Coroutine *cor, void *value, bool early){
int r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Waiting);
cor->entry_param = value;
cor->state = Coroutine_Running;
List_Remove(&cor->link);
if ( early ) {
List_AddHead(&g_c.runable, &cor->link);
} else {
List_AddTail(&g_c.runable, &cor->link);
}
r = pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
Semaphore_Release(&g_c.waiting_sem);
}
void *Coroutine_Yield(void *value){
int r = pthread_mutex_lock(&g_c.mutex);
assert(r == 0);
Coroutine *me = g_c.active;
assert(me && me->state == Coroutine_Running);
me->value = value;
me->state = Coroutine_Waiting;
List_Remove(&me->link);
List_AddTail(&g_c.waiting, &me->link);
switch (setjmp(me->buf)){
case Chunk_Initial:
r = pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
me->on_yield(me->this);
Coroutine_RunNext();
case Chunk_Create:
assert(false);
case Chunk_Enter:
// arrive here with mutex locked
g_c.active = me;
// when we return here - we are running again
assert(me->state == Coroutine_Running);
void *res = me->entry_param;
r = pthread_mutex_unlock(&g_c.mutex);
assert(r == 0);
return res;
}
return NULL;
}
void *Coroutine_GetValue(Coroutine *cor){
return cor->value;
}
Coroutine *Coroutine_GetActive()
{
return g_c.active;
}
bool Coroutine_IsRunning(Coroutine *cor)
{
int state = cor->state;
return state == Coroutine_Running || state == Coroutine_Waiting;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#include "coroutine.h"
#include <assert.h>
#include <setjmp.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include "cor_thread_local.h"
static void *mustmalloc(size_t size){
void *p = malloc(size);
assert(p);
return p;
}
#define New(type, ...) (type##_ctor((type *)mustmalloc(sizeof(type), ## __VA_ARGS__)))
#define Delete(ptr, type) ((ptr) ? (type##_dtor(ptr), free(ptr), (ptr) = NULL) : (void)0)
///////////////////////////////////////////////////////////////////////////////
// Semaphore built from mutex & condition variables...
//
// Using pthread.h (more widely available than the C standard library thread.h)
///////////////////////////////////////////////////////////////////////////////
typedef struct Semaphore {
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} Semaphore;
static void Semaphore_ctor(Semaphore *sem, int initial_count){
sem->count = initial_count;
int r = pthread_mutex_init(&sem->mutex, NULL);
assert(r == 0);
r = pthread_cond_init(&sem->cond, NULL);
assert(r == 0);
}
static void Semaphore_dtor(Semaphore *sem){
int r = pthread_mutex_destroy(&sem->mutex);
assert(r == 0);
r = pthread_cond_destroy(&sem->cond);
assert(r == 0);
}
static void Semaphore_Claim(Semaphore *sem){
int r = pthread_mutex_lock(&sem->mutex);
assert(r == 0);
while (sem->count <= 0) {
r = pthread_cond_wait(&sem->cond, &sem->mutex);
assert(r == 0);
}
sem->count--;
r = pthread_mutex_unlock(&sem->mutex);
assert(r == 0);
}
static void Semaphore_Release(Semaphore *sem){
int r = pthread_mutex_lock(&sem->mutex);
assert(r == 0);
sem->count++;
r = pthread_cond_broadcast(&sem->cond);
assert(r == 0);
r = pthread_mutex_unlock(&sem->mutex);
assert(r == 0);
}
///////////////////////////////////////////////////////////////////////////////
// ...semaphore built from mutex
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// 2-way linked lists...
//
// Brought inline here to avoid namespace polution
///////////////////////////////////////////////////////////////////////////////
typedef struct List_Link List_Link;
struct List_Link {
List_Link *next;
List_Link *prev;
};
typedef struct List_Head List_Head;
struct List_Head {
union {
struct {
List_Link link;
List_Link *filler;
} fwd;
struct {
List_Link *filler;
List_Link link;
} back;
};
};
static inline bool List_IsEmpty(const List_Head *list) {
return list->fwd.link.next == &list->back.link;
}
static inline List_Link *List_GetHead(const List_Head *list) {
return List_IsEmpty(list) ? NULL : list->fwd.link.next;
}
static inline List_Link *List_GetTail(const List_Head *list) {
return List_IsEmpty(list) ? NULL : list->back.link.prev;
}
#define OFFSETOF(Container, Field) ((char *)&((Container *)4)->Field - (char *)(Container *)4)
#define List_Link_Container(Container, Link, link) ((Container *)((char *)(link) - OFFSETOF(Container, Link)))
static inline void List_Init(List_Head *list)
{
list->fwd.link.next = &list->back.link;
list->fwd.link.prev = NULL;
list->back.link.prev = &list->fwd.link;
}
static inline void List_AddHead(List_Head *list, List_Link *link)
{
List_Link *first = list->fwd.link.next;
link->next = first;
link->prev = &list->fwd.link;
first->prev = link;
list->fwd.link.next = link;
}
static inline void List_AddTail(List_Head *list, List_Link *link)
{
List_Link *last = list->back.link.prev;
link->prev = last;
link->next = &list->back.link;
last->next = link;
list->back.link.prev = link;
}
static inline void List_Remove(List_Link *link)
{
link->prev->next = link->next;
link->next->prev = link->prev;
}
///////////////////////////////////////////////////////////////////////////////
// ...2-way linked lists
///////////////////////////////////////////////////////////////////////////////
typedef struct Coroutines Coroutines;
enum {
Coroutines_Idle,
Coroutines_Starting,
Coroutines_Started,
Coroutines_Active,
Coroutines_Stopping
};
enum {
Chunk_Initial,
Chunk_Create,
Chunk_Enter
};
enum {
Coroutine_Constructing,
Coroutine_Free,
Coroutine_Idle,
Coroutine_Running,
Coroutine_Waiting,
Coroutine_Complete
};
enum {
Coroutines_Init,
Coroutines_AllocatedChunk,
Coroutines_CoroutineComplete,
};
struct Coroutine {
Coroutines *coroutines;
List_Link link;
jmp_buf buf;
void *this;
Coroutine_Start start;
void *entry_param;
void *value;
char state;
char action;
};
struct Coroutines {
pthread_mutex_t mutex;
jmp_buf controller;
jmp_buf chunk_allocated;
// singletons
Coroutine *tip; // top of stack chunk
Coroutine *active; // currently running coroutine
Coroutine *primary; // Coroutine_Run coroutine
// lists
List_Head free;
List_Head inactive; // idle or complete
List_Head runable; // running or waiting to run
List_Head waiting; // yielded / waiting to run
Semaphore waiting_sem;
// state
char state;
};
_Cor_thread_local Coroutines *g_c;
static void stack_chunk_chunk(Coroutine *parent);
static void stack_chunk_base(Coroutine *parent);
static void Coroutine_PrimeStackChunks()
{
unsigned char chunk_of_stack[COROUTINE_STACK_SIZE];
chunk_of_stack[0] = 0xde;
chunk_of_stack[1] = 0xad;
chunk_of_stack[2] = 0xbe;
chunk_of_stack[3] = 0xef;
chunk_of_stack[COROUTINE_STACK_SIZE - 4] = 0xde;
chunk_of_stack[COROUTINE_STACK_SIZE - 3] = 0xad;
chunk_of_stack[COROUTINE_STACK_SIZE - 2] = 0xbe;
chunk_of_stack[COROUTINE_STACK_SIZE - 1] = 0xef;
stack_chunk_base(NULL);
}
static void stack_chunk_chunk(
Coroutine *parent
){
unsigned char chunk_of_stack[COROUTINE_STACK_SIZE];
chunk_of_stack[0] = 0xde;
chunk_of_stack[1] = 0xad;
chunk_of_stack[2] = 0xbe;
chunk_of_stack[3] = 0xef;
chunk_of_stack[COROUTINE_STACK_SIZE - 4] = 0xde;
chunk_of_stack[COROUTINE_STACK_SIZE - 3] = 0xad;
chunk_of_stack[COROUTINE_STACK_SIZE - 2] = 0xbe;
chunk_of_stack[COROUTINE_STACK_SIZE - 1] = 0xef;
stack_chunk_base(parent);
}
static void Coroutine_RunNext()
{
// arrvie here with mutex unlocked
Semaphore_Claim(&g_c->waiting_sem);
int r = pthread_mutex_lock(&g_c->mutex);
assert(r == 0);
assert(!List_IsEmpty(&g_c->runable));
Coroutine *next = List_Link_Container(Coroutine, link, List_GetHead(&g_c->runable));
assert(next->state == Coroutine_Running);
longjmp(next->buf, Chunk_Enter);
assert(false);
}
static void stack_chunk_base(
Coroutine *parent
){
Coroutine here;
here.state = Coroutine_Constructing;
switch (setjmp(here.buf)) {
case Chunk_Initial:
// got here for the first time
// parent now has a chunk_of_stack - add it to the free list
if (parent) {
assert(parent->state == Coroutine_Constructing);
parent->state = Coroutine_Free;
List_AddHead(&g_c->free, &parent->link);
}
// note that here is the tip of the chunk-claim stack
here.coroutines = g_c;
g_c->tip = &here;
// return to the coroutine allocator
longjmp(g_c->chunk_allocated, 1);
case Chunk_Create:
// request to create a new chunk on the stack
assert(here.state == Coroutine_Constructing);
stack_chunk_chunk(&here);
assert(false);
case Chunk_Enter:
// request to start a coroutine (ie use the chunk for a coroutine)
// arrive here with mutex locked
assert(here.state == Coroutine_Running);
g_c->active = &here;
int r = pthread_mutex_unlock(&g_c->mutex);
assert(r == 0);
here.value = here.start(here.entry_param);
r = pthread_mutex_lock(&g_c->mutex);
assert(r == 0);
g_c->active = NULL;
assert(here.state == Coroutine_Running);
List_Remove(&here.link);
here.state = Coroutine_Complete;
List_AddTail(&g_c->inactive, &here.link);
// coroutine has completed
if (g_c->primary == &here) {
// if primary coroutine - return to Coroutine_Run
longjmp(g_c->controller, Coroutines_CoroutineComplete);
}
r = pthread_mutex_unlock(&g_c->mutex);
assert(r == 0);
Coroutine_RunNext();
assert(false);
}
}
void Coroutine_StartSystem()
{
assert(!g_c);
g_c = mustmalloc(sizeof(Coroutines));
g_c->state = Coroutines_Starting;
pthread_mutexattr_t attr;
int r = pthread_mutexattr_init(&attr);
assert(r == 0);
r = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
assert(r == 0);
r = pthread_mutex_init(&g_c->mutex, &attr);
assert(r == 0);
r = pthread_mutexattr_destroy(&attr);
assert(r == 0);
g_c->tip = NULL;
g_c->active = NULL;
List_Init(&g_c->free);
List_Init(&g_c->inactive);
List_Init(&g_c->runable);
List_Init(&g_c->waiting);
Semaphore_ctor(&g_c->waiting_sem, 0);
// prime the chunk system
if (!setjmp(g_c->chunk_allocated)){
Coroutine_PrimeStackChunks();
assert(false);
}
assert(g_c->state == Coroutines_Starting);
g_c->state = Coroutines_Started;
}
void Coroutine_StopSystem()
{
int r = pthread_mutex_lock(&g_c->mutex);
assert(r == 0);
assert(g_c->state == Coroutines_Started);
g_c->state = Coroutines_Stopping;
assert(List_IsEmpty(&g_c->inactive));
Semaphore_dtor(&g_c->waiting_sem);
assert(g_c->state == Coroutines_Stopping);
pthread_mutex_unlock(&g_c->mutex);
assert(r == 0);
g_c->state = Coroutines_Idle;
r = pthread_mutex_destroy(&g_c->mutex);
assert(r == 0);
free(g_c);
g_c = NULL;
}
void *Coroutine_Run(
Coroutine *cor,
void *value
){
Coroutines *cors = cor->coroutines;
assert(g_c == cors);
int r = pthread_mutex_lock(&cors->mutex);
assert(r == 0);
assert(cors->state == Coroutines_Started);
cors->state = Coroutines_Active;
cors->primary = cor;
Coroutine_Continue(cors->primary, value, true);
if (!setjmp(cors->controller)){
pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
// start the first coroutine
Coroutine_RunNext();
}
// arrive here with mutex locked
assert(List_IsEmpty(&cors->runable));
assert(List_IsEmpty(&cors->waiting));
assert(cors->state == Coroutines_Active);
cors->state = Coroutines_Started;
pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
return Coroutine_GetValue(cor);
}
Coroutine *Coroutine_New(
Coroutine_Start start
){
assert(g_c->state == Coroutines_Started || g_c->state == Coroutines_Active);
// if none free - add one
if (List_IsEmpty(&g_c->free)){
if (!setjmp(g_c->chunk_allocated)){
longjmp(g_c->tip->buf, Chunk_Create);
}
}
Coroutine *cor = List_Link_Container(Coroutine, link, List_GetHead(&g_c->free));
assert(cor->state == Coroutine_Free);
cor->state = Coroutine_Idle;
cor->start = start;
cor->value = NULL;
List_Remove(&cor->link);
List_AddHead(&g_c->inactive, &cor->link);
return cor;
}
void Coroutine_Delete(
Coroutine *cor
){
Coroutines *cors = cor->coroutines;
int r = pthread_mutex_lock(&cors->mutex);
assert(r == 0);
assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Complete);
cor->state = Coroutine_Free;
List_Remove(&cor->link);
List_AddTail(&cors->free, &cor->link);
r = pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
}
void Coroutine_Continue(
Coroutine *cor,
void *value,
bool early
){
Coroutines *cors = cor->coroutines;
int r = pthread_mutex_lock(&cors->mutex);
assert(r == 0);
assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Waiting);
cor->entry_param = value;
cor->state = Coroutine_Running;
List_Remove(&cor->link);
if ( early ) {
List_AddHead(&cors->runable, &cor->link);
} else {
List_AddTail(&cors->runable, &cor->link);
}
r = pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
Semaphore_Release(&cors->waiting_sem);
}
void *Coroutine_Yield(
void *value,
Coroutine_YieldCallback on_yield,
void *this
){
int r = pthread_mutex_lock(&g_c->mutex);
assert(r == 0);
Coroutine *me = g_c->active;
Coroutines *cors = me->coroutines;
assert(me && me->state == Coroutine_Running && cors == g_c);
me->value = value;
me->state = Coroutine_Waiting;
List_Remove(&me->link);
List_AddTail(&cors->waiting, &me->link);
switch (setjmp(me->buf)){
case Chunk_Initial:
r = pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
on_yield(this);
Coroutine_RunNext();
case Chunk_Create:
assert(false);
case Chunk_Enter:
// arrive here with mutex locked
cors->active = me;
// when we return here - we are running again
assert(me->state == Coroutine_Running);
void *res = me->entry_param;
r = pthread_mutex_unlock(&cors->mutex);
assert(r == 0);
return res;
}
return NULL;
}
void *Coroutine_GetValue(
Coroutine *cor
){
return cor->value;
}
Coroutine *Coroutine_GetActive()
{
return g_c->active;
}
bool Coroutine_IsRunning(
Coroutine *cor
)
{
int state = cor->state;
return state == Coroutine_Running || state == Coroutine_Waiting;
}
trunk/coroutine/generator.c
11
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "generator.h"
#include "coroutine.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
enum {
Generator_Running,
Generator_Deleting,
Generator_Complete
};
struct Generator {
Coroutine *coroutine;
Coroutine *caller;
void *(*start)(void *);
void *param;
char state;
};
static void on_yield(void *this){
Generator *gen = (Generator *)this;
Coroutine_Continue(gen->caller, Coroutine_GetValue(gen->coroutine), true);
}
static void *do_start(void *this){
Generator *gen = (Generator *)this;
assert(gen->state == Generator_Running || gen->state == Generator_Deleting);
void *value;
if (gen->state == Generator_Running){
value = gen->start(gen->param);
} else {
// we are being deleted
value = NULL;
}
gen->state = Generator_Complete;
Coroutine_Continue(gen->caller, value, true);
return value;
}
Generator *Generator_New(void *(*start)(void *), void *param){
Generator *gen = malloc(sizeof(Generator));
gen->start = start;
gen->param = param;
gen->coroutine = Coroutine_New(gen, on_yield, do_start);
gen->state = Generator_Running;
return gen;
}
void Generator_Delete(Generator *gen){
assert(gen->state != Generator_Deleting);
if (gen->state == Generator_Running){
gen->state = Generator_Deleting;
gen->caller = Coroutine_GetActive();
Coroutine_Continue(gen->coroutine, gen, true);
Coroutine_Yield(NULL);
}
assert(gen->state == Generator_Complete);
Coroutine_Delete(gen->coroutine);
free(gen);
}
bool Generator_Next(Generator *gen, void **value){
assert(gen->state != Generator_Deleting);
if (gen->state == Generator_Complete){
return false;
}
gen->caller = Coroutine_GetActive();
Coroutine_Continue(gen->coroutine, gen, true);
*value = Coroutine_Yield(NULL);
return Coroutine_IsRunning(gen->coroutine);
}
bool Generator_Yield(void *value)
{
Generator *gen = Coroutine_Yield(value);
return gen->state == Generator_Running;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "generator.h"
#include "coroutine.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "cor_thread_local.h"
enum {
Generator_Running,
Generator_Deleting,
Generator_Complete
};
struct Generator {
Coroutine *coroutine;
Coroutine *caller;
void *(*start)(void *);
void *param;
char state;
};
_Cor_thread_local Generator *g_active_generator = NULL;
static void on_yield_gen(void *this){
Generator *gen = (Generator *)this;
Coroutine_Continue(gen->caller, Coroutine_GetValue(gen->coroutine), true);
}
static void on_yield_gen_caller(void *this){
(void)this;
}
static void *do_start(void *this){
Generator *gen = (Generator *)this;
g_active_generator = this;
assert(gen->state == Generator_Running || gen->state == Generator_Deleting);
void *value;
if (gen->state == Generator_Running){
g_active_generator = gen;
value = gen->start(gen->param);
g_active_generator = NULL;
} else {
// we are being deleted
value = NULL;
}
gen->state = Generator_Complete;
Coroutine_Continue(gen->caller, value, true);
return value;
}
Generator *Generator_New(void *(*start)(void *), void *param){
Generator *gen = malloc(sizeof(Generator));
gen->start = start;
gen->param = param;
gen->coroutine = Coroutine_New(do_start);
gen->state = Generator_Running;
return gen;
}
void Generator_Delete(Generator *gen){
assert(gen->state != Generator_Deleting);
if (gen->state == Generator_Running){
gen->state = Generator_Deleting;
gen->caller = Coroutine_GetActive();
Coroutine_Continue(gen->coroutine, gen, true);
Coroutine_Yield(NULL, on_yield_gen_caller, gen);
}
assert(gen->state == Generator_Complete);
Coroutine_Delete(gen->coroutine);
free(gen);
}
bool Generator_Next(Generator *gen, void **value){
assert(gen->state != Generator_Deleting);
if (gen->state == Generator_Complete){
return false;
}
gen->caller = Coroutine_GetActive();
Coroutine_Continue(gen->coroutine, gen, true);
*value = Coroutine_Yield(NULL, on_yield_gen_caller, gen);
return Coroutine_IsRunning(gen->coroutine);
}
bool Generator_Yield(void *value)
{
assert(g_active_generator);
Generator *gen = g_active_generator;
g_active_generator = NULL;
Coroutine_Yield(value, on_yield_gen, gen);
g_active_generator = gen;
return gen->state == Generator_Running;
}
trunk/examples/main.c
11
12
1
1
trunk/include/cor_thread_local.h
trunk/include/coroutine.h
11
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdbool.h>
typedef struct Coroutine Coroutine;
typedef void (*Coroutine_YieldCallback)(void *this);
typedef void *(*Coroutine_Start)(void *);
void Coroutine_StartSystem();
void Coroutine_StopSystem();
Coroutine *Coroutine_New(void *this, Coroutine_YieldCallback on_yield, Coroutine_Start start);
void *Coroutine_Run(Coroutine *cor, void *value);
void Coroutine_Delete(Coroutine *cor);
void Coroutine_Continue(Coroutine *cor, void *value, bool early);
void *Coroutine_Yield(void *value);
void *Coroutine_GetValue(Coroutine *cor);
Coroutine *Coroutine_GetActive();
bool Coroutine_IsRunning(Coroutine *cor);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#ifndef COROUTINE_H
#define COROUTINE_H
#include <stdbool.h>
///////////////////////////////////////////////////////////////////////////////
// Coroutine
//
// Coroutines for C, based on setjmp/longjmp.
// Thread safe - each thread has its own coroutine system
// Coroutines are cooperatively scheduled
// Coroutines have their own stack (currently 16K each)
// A coroutine can be continued, queried, or deleted on a different thread.
//
// Usage:
// Coroutine_StartSystem(); // call once per thread before using coroutines
// Coroutine *co = Coroutine_New(start_function);
// void *result = Coroutine_Run(co, initial_value);
// Coroutine_Delete(co);
// Coroutine_StopSystem(); // call once per thread when done with coroutines
//
// Inside the coroutine function:
// void *value = Coroutine_Yield(yield_value, on_yield, this);
// ...
// return return_value;
//
// To create a coroutine:
// Coroutine *co = Coroutine_New(start_function);
// To start or continue a coroutine:
// void *result = Coroutine_Continue(co, value, early);
// // early=true puts the coroutine at the head of the run queue
// // early=false puts the coroutine at the tail of the run queue
// To yield from inside a coroutine:
// void *value = Coroutine_Yield(yield_value, on_yield, this);
// // on_yield is called before the next coroutine is run
// // 'this' is passed to on_yield as its parameter
// // value is the value passed to Coroutine_Continue
// To delete a coroutine:
// Coroutine_Delete(co);
// To get the value yielded from, or returned by a corotuine:
// void *value = Coroutine_GetValue(co);
// To get the currently running coroutine (NULL if none):
// Coroutine *co = Coroutine_GetActive();
// To check if a coroutine is currently running:
// bool running = Coroutine_IsRunning(co);
//
// Notes:
// Coroutine is not expected to be used directly, but as a foundation for
// higher level constructs such as Generators, Async, etc.
//
///////////////////////////////////////////////////////////////////////////////
// The stack is used as follows:
// +------------------+ <- stack top
// | coroutine header | <- more claimed as needed in Coroutine_New
// +------------------+ <-
// | coroutine stack | <-
// +------------------+ <-
// | coroutine header |
// +------------------+
// | coroutine stack |
// +------------------+
// | coroutine header |
// +------------------+
// | coroutine stack |
// +------------------+
// | coroutine header |
// +------------------+
// | coroutine stack |
// +------------------+
// | coroutine header |
// +------------------+
// | startup space | <- set aside by Coroutine_StartSystem
// +------------------+
// | caller | <- This calls Coroutine_StartSystem etc
// +------------------+
// | used stack |
// +------------------+ <- stack bottom
// Each coroutine has this much stack:
#define COROUTINE_STACK_SIZE 16384
// When Coroutines is started, an amount of stack is set aside to give
// the caller of Coroutine_StartSystem a bit of room to work before calling
// Coroutine_Run(), that is this amount:
#define COROUTINE_STARTUP_STACK_SIZE 1024
typedef struct Coroutine Coroutine;
typedef void (*Coroutine_YieldCallback)(void *this);
typedef void *(*Coroutine_Start)(void *);
void Coroutine_StartSystem();
void Coroutine_StopSystem();
Coroutine *Coroutine_New(Coroutine_Start start);
void *Coroutine_Run(Coroutine *cor, void *value);
void Coroutine_Delete(Coroutine *cor);
void Coroutine_Continue(Coroutine *cor, void *value, bool early);
void *Coroutine_Yield(void *value, Coroutine_YieldCallback on_yield, void *this);
void *Coroutine_GetValue(Coroutine *cor);
Coroutine *Coroutine_GetActive();
bool Coroutine_IsRunning(Coroutine *cor);
#endif
trunk/include/generator.h
11
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdbool.h>
typedef struct Generator Generator;
Generator *Generator_New(void *(*)(void *), void *);
void Generator_Delete(Generator *);
// Returns true if generator yielded a value, false if generator is complete
// *value is set to generator's value (yield / return value from exit)
bool Generator_Next(Generator *, void **value);
// Yield a value from the generator
// Returns true if generator should continue, false for generator to exit PDQ
bool Generator_Yield(void *);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef GENERATOR_H
#define GENERATOR_H
#include <stdbool.h>
typedef struct Generator Generator;
Generator *Generator_New(void *(*)(void *), void *);
void Generator_Delete(Generator *);
// Returns true if generator yielded a value, false if generator is complete
// *value is set to generator's value (yield / return value from exit)
bool Generator_Next(Generator *, void **value);
// Yield a value from the generator
// Returns true if generator should continue, false for generator to exit PDQ
bool Generator_Yield(void *);
#endif