libfiber [1] is an (alpha quality!) user-space cooperative threading library in C, complete with asynchonous I/O support. It allow you to run multiple concurrent fibers, each with its own fixed stack, and switch between them automatically during I/O calls, or manually via fib_yield().
libfiber supports i386 and amd64 processors, and works under Windows, Linux, and FreeBSD (should probably work under other *BSD systems too).
libfiber implements its set of network I/O opearations using platform’s native asynchronous I/O APIs. It uses kqueue under *BSD, epoll under Linux, and IO Completion Ports under Windows.
Here’s the coroutine part of the API (see fiber.h):
typedef void *fiber_t;
fiber_t fib_create(void (*fn)(void*), void *arg, int stack);
fiber_t fib_current(void);
void fib_yield(void);
void fib_suspend(void);
void fib_sleep(long milliseconds);
void fib_resume(fiber_t fiber);
void fib_exit(void);
void fib_schedule(void);
long long fib_clock();
... and here’s the network I/O part of the API:
enum fio_socktype {
FIO_SOCK_STREAM,
FIO_SOCK_DGRAM,
FIO_SOCK_SEQPACKET
};
enum {
FIO_ADDRSTRLEN = 48,
FIO_SERVSTRLEN = 8
};
int fio_announce(enum fio_socktype st,
const char *addr, const char *serv);
int fio_accept(int socket, char *addr, char *serv);
int fio_connect(enum fio_socktype st,
const char *addr, const char *port);
int fio_getlocaladdr(int socket, char *addr, char *serv);
int fio_getremoteaddr(int socket, char *addr, char *serv);
int fio_recv(int socket, void *buf, int size);
int fio_recvall(int socket, void *buf, int size);
int fio_send(int socket, const void *buf, int size);
int fio_sendall(int socket, const void *buf, int size);
void fio_close(int socket);
Also take a look at the examples directory in the sources for a number of examples.
To build libfiber, first obtain its sources either from [1], or directly via mercurial like this:
hg clone http://hg.tx97.net/libfiber/
Then run the configure script to specify your platform:
sh configure {i386|amd64} {bsd|linux|windows}
Finally build the library by running:
make
If all goes well, you’ll get a libfiber.a file, which you’ll be able to link your programs against.
A set of example programs will also be built; look them up in the examples directory.
There are multiple other libraries similar to libfiber. The closest one is probably libtask [2]; others include libconcurrency [3], libcoro [4] and GNU Pth [5].
libfiber differs from those libraries by:
supporting Windows;
using native asyncronous I/O APIs;
being reasonably fast;
not being portable;
not being comprehensive;
not being well tested.