纯 C 编写的单头堆栈跨平台协程库。
Minicoro is single-file library for using asymmetric coroutines in C. The API is inspired by Lua coroutines but with C use in mind.
The project is being developed mainly to be a coroutine backend for the Nelua programming language.
The library assembly implementation is inspired by Lua Coco by Mike Pall.
Most platforms are supported through different methods:
| Platform | Assembly Method | Fallback Method |
|---|---|---|
| Android | ARM/ARM64 | N/A |
| iOS | ARM/ARM64 | N/A |
| Windows | x86_64 | Windows fibers |
| Linux | x86_64/i686 | ucontext |
| Mac OS X | x86_64/ARM/ARM64 | ucontext |
| WebAssembly | N/A | Emscripten fibers / Binaryen asyncify |
| Raspberry Pi | ARM | ucontext |
| RISC-V | rv64/rv32 | ucontext |
The assembly method is used by default if supported by the compiler and CPU, otherwise ucontext or fiber method is used as a fallback.
The assembly method is very efficient, it just take a few cycles to create, resume, yield or destroy a coroutine.
mco_coro object is not thread safe, you should use a mutex for manipulating it in multithread applications.thread_local qualifier.thread_local inside coroutine code, the compiler may cache thread local variables pointers which can be invalid when a coroutine switch threads.-s ASYNCIFY=1.A coroutine represents an independent "green" thread of execution. Unlike threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function.
You create a coroutine by calling mco_create.
Its sole argument is a mco_desc structure with a description for the coroutine.
The mco_create function only creates a new coroutine and returns a handle to it, it does not start the coroutine.
You execute a coroutine by calling mco_resume.
When calling a resume function the coroutine starts its execution by calling its body function.
After the coroutine starts running, it runs until it terminates or yields.
A coroutine yields by calling mco_yield.
When a coroutine yields, the corresponding resume returns immediately,
even if the yield happens inside nested function calls (that is, not in the main function).
The next time you resume the same coroutine, it continues its execution from the point where it yielded.
To associate a persistent value with the coroutine,
you can optionally set user_data on its creation and later retrieve with mco_get_user_data.
To pass values between resume and yield,
you can optionally use mco_push and mco_pop APIs,
they are intended to pass temporary values using a LIFO style buffer.
The storage system can also be used to send and receive initial values on coroutine creation or before it finishes.
To use minicoro, do the following in one .c file:
#define MINICORO_IMPL
#include "minicoro.h"
You can do #include "minicoro.h" in other parts of the program just like any other header.
The following simple example demonstrates on how to use the library:
…
NOTE: In case you don't want to use the minicoro allocator system you should
allocate a coroutine object yourself using mco_desc.coro_size and call mco_init,
then later to destroy call mco_uninit and deallocate it.
You can yield the current running coroutine from anywhere
without having to pass mco_coro pointers around,
to this just use mco_yield(mco_running()).
The library has the storage interface to assist passing data between yield and resume.
It's usage is straightforward,
use mco_push to send data before a mco_resume or mco_yield,
then later use mco_pop after a mco_resume or mco_yield to receive data.
Take care to not mismatch a push and pop, otherwise these functions will return
an error.
The library return error codes in most of its API in case of misuse or system error, the user is encouraged to handle them properly.
The new compile time option MCO_USE_VMEM_ALLOCATOR enables a virtual memory backed allocator.
Every stackful coroutine usually have to reserve memory for its full stack, this typically makes the total memory usage very high when allocating thousands of coroutines, for example, an application with 100 thousands coroutine with stacks of 56KB would consume as high as 5GB of memory, however your application may not really full stack usage for every coroutine.
Some developers often prefer stackless coroutines over stackful coroutines because of this problem, stackless memory footprint is low, therefore often considered more lightweight. However stackless have many other limitations, like you cannot run unconstrained code inside them.
One remedy to the solution is to make stackful coroutines growable, to only use physical memory on demand when its really needed, and there is a nice way to do this relying on virtual memory allocation when supported by the operating system.
The virtual memory backed allocator will reserve virtual memory in the OS for each coroutine stack, but not trigger real physical memory usage yet. While the application virtual memory usage will be high, the physical memory usage will be low and actually grow on demand (usually every 4KB chunk in Linux).
The virtual memory backed allocator also raises the default stack size to about 2MB, typically the size of extra threads in Linux, so you have more space in your coroutines and the risk of stack overflow is low.
As an example, allocating 100 thousands coroutines with nearly 2MB stack reserved space with the virtual memory allocator uses 783MB of physical memory usage, that is about 8KB per coroutine, however the virtual memory usage will be at 98GB.
It is recommended to enable this option only if you plan to spawn thousands of coroutines while wanting to have a low memory footprint. Not all environments have an OS with virtual memory support, therefore this option is disabled by default.
This option may add an order of magnitude overhead to mco_create()/mco_destroy(),
because they will request the OS to manage virtual memory page tables,
if this is a problem for you, please customize a custom allocator for your own needs.
The following can be defined to change the library behavior:
MCO_API - Public API qualifier. Default is extern.MCO_MIN_STACK_SIZE - Minimum stack size when creating a coroutine. Default is 32768 (32KB).MCO_DEFAULT_STORAGE_SIZE - Size of coroutine storage buffer. Default is 1024.MCO_DEFAULT_STACK_SIZE - Default stack size when creating a coroutine. Default is 57344 (56KB). When MCO_USE_VMEM_ALLOCATOR is true the default is 2040KB (nearly 2MB).MCO_ALLOC - Default allocation function. Default is calloc.MCO_DEALLOC - Default deallocation function. Default is free.MCO_USE_VMEM_ALLOCATOR - Use virtual memory backed allocator, improving memory footprint per coroutine.MCO_NO_DEFAULT_ALLOCATOR - Disable the default allocator using MCO_ALLOC and MCO_DEALLOC.MCO_ZERO_MEMORY - Zero memory of stack when poping storage, intended for garbage collected environments.MCO_DEBUG - Enable debug mode, logging any runtime error to stdout. Defined automatically unless NDEBUG or MCO_NO_DEBUG is defined.MCO_NO_DEBUG - Disable debug mode.MCO_NO_MULTITHREAD - Disable multithread usage. Multithread is supported when thread_local is supported.MCO_USE_ASM - Force use of assembly context switch implementation.MCO_USE_UCONTEXT - Force use of ucontext context switch implementation.MCO_USE_FIBERS - Force use of fibers context switch implementation.MCO_USE_ASYNCIFY - Force use of Binaryen asyncify context switch implementation.MCO_USE_VALGRIND - Define if you want run with valgrind to fix accessing memory errors.The coroutine library was benchmarked for x86_64 counting CPU cycles for context switch (triggered in resume or yield) and initialization.
| CPU Arch | OS | Method | Context switch | Initialize | Uninitialize |
|---|---|---|---|---|---|
| x86_64 | Linux | assembly | 9 cycles | 31 cycles | 14 cycles |
| x86_64 | Linux | ucontext | 352 cycles | 383 cycles | 14 cycles |
| x86_64 | Windows | fibers | 69 cycles | 10564 cycles | 11167 cycles |
| x86_64 | Windows | assembly | 33 cycles | 74 cycles | 14 cycles |
NOTE: Tested on Intel Core i7-8750H CPU @ 2.20GHz with pre allocated coroutines.
Here is a list of all library functions for quick reference:
…
The following is a more complete example, generating Fibonacci numbers:
…
MCO_USE_VMEM_ALLOCATOR option for allocating thousands of coroutines with low memory footprint, this include breaking changes in the allocator API.暂无开放 Issues,或尚未同步最近议题。