Fork me on GitHub

Team(.cpp)

Introduction

Team is a library that adds coroutines and async semantics to C++.

By “async”, I mean that that when your program needs to wait for external stuff (like sending data over a network), it can work on other things at the same time. (E.g. a web server can start handling a request from one client while it waits for another to finish receiving its response).

By “coroutines”, I mean independent threads of execution that can pause when they need to wait. You write code in a linear way — no callbacks. Team introduces a new keyword, async, to indicate when something should happen asynchronously with respect to the code around it.

Check out this example program:

#include <team>
#include <iostream>

using namespace std;
using namespace team;

void doWork() {
    sleep(1);
}

int main() {
    await {
        for (auto i : range(10)) {
            async { doWork(); };
        }
    }
}

It takes about one second to run because all of the sleep()s happen at the same time: when doWork() calls sleep(), control jumps back outside the nearest async block, and in this case the for loop keeps going. await is a little tool that keeps track of the tasks that were started inside it, and waits for them all to finish before continuing.

Team comes with (in progress) bindings to libuv, which is a library for doing stuff like sleep(), network access, and filesystem access asynchronously. Here’s a little web server that uses them:

#include <team/http>

int main() {
    HTTP::Server('0.0.0.0', 8000)
        .serve([](auto req, auto res) {
            res.send("Hello, World!");
        });
}

You could add a blocking thing like sleep(1) or lookUpSessionInDatabase() before res.send(), and it won’t stop the web server from handling other requests at the same time.

Team is a work in progress and I think it could be a powerful programming tool. It’s heavily inspired by Tame (which I use at work) and gevent. If you have ideas or want to talk about it, email me at [email protected].