Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/libsnes/bsnes/libco/ucontext.c
2 views
1
/*
2
libco.ucontext (2008-01-28)
3
author: Nach
4
license: public domain
5
*/
6
7
/*
8
* WARNING: the overhead of POSIX ucontext is very high,
9
* assembly versions of libco or libco_sjlj should be much faster
10
*
11
* This library only exists for two reasons:
12
* 1 - as an initial test for the viability of a ucontext implementation
13
* 2 - to demonstrate the power and speed of libco over existing implementations,
14
* such as pth (which defaults to wrapping ucontext on unix targets)
15
*
16
* Use this library only as a *last resort*
17
*/
18
19
#define LIBCO_C
20
#include "libco.h"
21
#include <stdlib.h>
22
#include <ucontext.h>
23
24
#ifdef __cplusplus
25
extern "C" {
26
#endif
27
28
static thread_local ucontext_t co_primary;
29
static thread_local ucontext_t *co_running = 0;
30
31
cothread_t co_active() {
32
if(!co_running) co_running = &co_primary;
33
return (cothread_t)co_running;
34
}
35
36
cothread_t co_create(unsigned int heapsize, void (*coentry)(void)) {
37
if(!co_running) co_running = &co_primary;
38
ucontext_t *thread = (ucontext_t*)malloc(sizeof(ucontext_t));
39
if(thread) {
40
if((!getcontext(thread) && !(thread->uc_stack.ss_sp = 0)) && (thread->uc_stack.ss_sp = malloc(heapsize))) {
41
thread->uc_link = co_running;
42
thread->uc_stack.ss_size = heapsize;
43
makecontext(thread, coentry, 0);
44
} else {
45
co_delete((cothread_t)thread);
46
thread = 0;
47
}
48
}
49
return (cothread_t)thread;
50
}
51
52
void co_delete(cothread_t cothread) {
53
if(cothread) {
54
if(((ucontext_t*)cothread)->uc_stack.ss_sp) { free(((ucontext_t*)cothread)->uc_stack.ss_sp); }
55
free(cothread);
56
}
57
}
58
59
void co_switch(cothread_t cothread) {
60
ucontext_t *old_thread = co_running;
61
co_running = (ucontext_t*)cothread;
62
swapcontext(old_thread, co_running);
63
}
64
65
#ifdef __cplusplus
66
}
67
#endif
68
69