Programming Library — libco

libco is a cooperative-multithreading library written in C89. There are many uses for cooperative-multithreading, but the principle use is to replace complex state machines with safe multi-tasking threads.

The way this works is that you can create new stack frames, which can have their own call trees. At any time, an active thread can switch to any other thread. Said thread can then be resumed immediately after it switched when it is activated once again.

In contrast to preemptive-multithreading, this model only utilizes one physical CPU thread. Although this disallows true multi-core parallelism, it also completely bypasses race conditions; and synchronizing between threads is literally hundreds of times faster than atomic locks between actual CPU cores.

libco is particularly suited to tasks that require millions of switches or synchronizations per second. It has been written to be as fast as possible. For instance, the x86 co_switch function (which saves the state of the previous thread, restores the state of the new thread, and resumes execution on the new thread) is implemented in a mere ten CPU instructions.

The API consists of a mere four functions: create, delete, active and switch. Thread handles are a simple void* block of allocated memory. This minimalism results in a perfectly stable API that has not changed in nearly a decade, and a package download that is less than 10KB in size. Only the functions that cannot be implemented in ISO-C89 are provided. No attempts are made at implementing scheduling services or other extraneous functionality. This seems particularly fitting as most cooperative-threading applications tend to implement their own schedulers anyway.

Note: this concept tends to go by countless names. Some of the most popular are: cooperative-threads, green threads, fibers, coroutines, etc. The version implemented by libco is backed by a unique stack for each thread.


As cooperative-threading is not officially possible using pure ISO-C89, backends for each supported target are needed. To that aim, libco provides the following backends:


libco has been used in the following software:

If you are using libco in a serious public-facing project and would be willing to be noted here, please let me know on the forums.


libco is available under the ISC license.


libco v16 (2010-12-24)

Note: libco is not by any means discontinued. It is simply very stable and does not require many updates.