Goroutines in Lua

A goroutine is a lightweight thread of execution.

function f(from)
    for i = 0, 2 do
        print(from .. ":", i)
    end
end

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct")

To invoke this function in a coroutine, use coroutine.create(f). This new coroutine will execute concurrently with the calling one.

co = coroutine.create(function() f("coroutine") end)
coroutine.resume(co)

You can also start a coroutine for an anonymous function call.

co2 = coroutine.create(function(msg)
    print(msg)
end)
coroutine.resume(co2, "going")

Our two function calls are running asynchronously in separate coroutines now. Wait for them to finish.

-- Lua doesn't have a built-in sleep function like Go.
-- We can use os.execute to pause for a second but it's not ideal for concurrency.
os.execute("sleep 1")
print("done")

When we run this program, we see the output of the blocking call first, then the output of the two coroutines. The coroutines’ output may be interleaved, because coroutines are being run concurrently by the Lua runtime.

$ lua goroutines.lua
direct : 0
direct : 1
direct : 2
coroutine : 0
going
coroutine : 1
coroutine : 2
done

Next we’ll look at a complement to coroutines in concurrent Lua programs: channels (or similar concepts like queues).