extrawurst's blog

#dlang Fibers and a lightweight eventloop

• dlang, gamedev, events, and fibers

###D and Fibers

Fibers are D’s concept for resumable functions and the barebone behind the popular event driven framework vibe.d. In the unecht project I recently added a generic system to use resumable functions much like Unity3D supports it using their coroutine system. In Unity3D a simple usage example is this:

IEnumerator DeferedPrint() {
    yield return new WaitForSeconds(1f);
    Debug.Log("... 1s later");
// start the coroutine:

The same behaviour in D and unecht looks like this:

void DeferedPrint() {
    writefln("... 1s later");
// start the fiber:

###Lightweight Eventloop

The eventloop necessary to allow this is simply resuming all active fibers each frame. The main addition to the Fibers in the standard library is that each Fiber can have a child Fiber that has to finish before the parent Fiber can resume. Following code shows a practical example:

static void removeOnePerX()
            while(ballRoot.sceneNode.children.length > 0)

This way the execution of a single function can be defered over a specific time span. The result of that example is demonstrated here: fibers demo

The whole code of this is available on github here

comments powered by Disqus