Goroutines in Lua
A goroutine is a lightweight thread of execution.
Suppose we have a function call f(s)
. Here’s how we’d call that in the usual way, running it synchronously.
To invoke this function in a coroutine, use coroutine.create(f)
. This new coroutine will execute concurrently with the calling one.
You can also start a coroutine for an anonymous function call.
Our two function calls are running asynchronously in separate coroutines now. Wait for them to finish.
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.
Next we’ll look at a complement to coroutines in concurrent Lua programs: channels (or similar concepts like queues).