libfiber

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 it's 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 it's 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.

How to use it

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.

How to build it

To build libfiber, first obtain it's 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.

See also

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:

References

  1. http://hg.tx97.net/libfiber/
  2. http://swtch.com/libtask/
  3. http://code.google.com/p/libconcurrency/
  4. http://software.schmorp.de/pkg/libcoro.html
  5. http://www.gnu.org/software/pth/