| 1 | /* |
| 2 | libco.win (2008-01-28) |
| 3 | authors: Nach, byuu |
| 4 | license: public domain |
| 5 | */ |
| 6 | |
| 7 | #define LIBCO_C |
| 8 | #include <libco.h> |
| 9 | #define WINVER 0x0400 |
| 10 | #define _WIN32_WINNT 0x0400 |
| 11 | #define WIN32_LEAN_AND_MEAN |
| 12 | #include <windows.h> |
| 13 | |
| 14 | #ifdef __cplusplus |
| 15 | extern "C" { |
| 16 | #endif |
| 17 | |
| 18 | static thread_local cothread_t co_active_ = 0; |
| 19 | |
| 20 | static void __stdcall co_thunk(void *coentry) |
| 21 | { |
| 22 | ((void (*)(void))coentry)(); |
| 23 | } |
| 24 | |
| 25 | cothread_t co_active(void) |
| 26 | { |
| 27 | if (!co_active_) |
| 28 | { |
| 29 | #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) |
| 30 | ConvertThreadToFiberEx(0, FIBER_FLAG_FLOAT_SWITCH); |
| 31 | #else |
| 32 | ConvertThreadToFiber(0); |
| 33 | #endif |
| 34 | co_active_ = GetCurrentFiber(); |
| 35 | } |
| 36 | return co_active_; |
| 37 | } |
| 38 | |
| 39 | cothread_t co_create(unsigned int heapsize, void (*coentry)(void)) |
| 40 | { |
| 41 | if (!co_active_) |
| 42 | { |
| 43 | #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) |
| 44 | ConvertThreadToFiberEx(0, FIBER_FLAG_FLOAT_SWITCH); |
| 45 | #else |
| 46 | ConvertThreadToFiber(0); |
| 47 | #endif |
| 48 | co_active_ = GetCurrentFiber(); |
| 49 | } |
| 50 | |
| 51 | #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) |
| 52 | return (cothread_t)CreateFiberEx(heapsize, heapsize, FIBER_FLAG_FLOAT_SWITCH, co_thunk, (void*)coentry); |
| 53 | #else |
| 54 | return (cothread_t)CreateFiber(heapsize, co_thunk, (void*)coentry); |
| 55 | #endif |
| 56 | } |
| 57 | |
| 58 | void co_delete(cothread_t cothread) |
| 59 | { |
| 60 | DeleteFiber(cothread); |
| 61 | } |
| 62 | |
| 63 | void co_switch(cothread_t cothread) |
| 64 | { |
| 65 | co_active_ = cothread; |
| 66 | SwitchToFiber(cothread); |
| 67 | } |
| 68 | |
| 69 | #ifdef __cplusplus |
| 70 | } |
| 71 | #endif |