Building an Asynchronous Task Event Loop

Building an Asynchronous Task Event Loop in Lua: Game engines (like Roblox with and ) and web servers (like OpenResty / NGINX) achieve non-blocking concurrency…

Game engines (like Roblox with task.wait() and task.spawn()) and web servers (like OpenResty / NGINX) achieve non-blocking concurrency across tens of thousands of connections on a single OS thread using Coroutine Task Schedulers.


Architecture of a Coroutine Event Loop

                          [ Task Queue ]
                                |
             +------------------+------------------+
             |                                     |
       [ Task 1 (co) ]                       [ Task 2 (co) ]
             |                                     |
             v                                     v
       coroutine.resume                      coroutine.resume
             |                                     |
        Calls wait(2.5)                       Finishes Work
             |                                     |
             v                                     v
       Yields to Scheduler                    Marks Status 'dead'
       (Re-queued with Wakeup Time)           (Garbage Collected)

Implementation: The Time-Aware Task Scheduler

local Scheduler = {
    tasks = {}, -- Active ready queue
    waiting = {} -- Tasks waiting for a sleep timer
}

-- Spawn a non-blocking background task
function Scheduler.spawn(taskFn, ...)
    local co = coroutine.create(taskFn)
    table.insert(Scheduler.tasks, { co = co, args = {...} })
    return co
end

-- Sleep function callable inside any coroutine
function Scheduler.sleep(seconds)
    local wakeupTime = os.clock() + seconds
    coroutine.yield("SLEEP", wakeupTime)
end

-- The Main Engine Tick
function Scheduler.tick()
    local now = os.clock()

    -- 1. Check waiting tasks whose timer has expired
    for i = #Scheduler.waiting, 1, -1 do
        local item = Scheduler.waiting[i]
        if now >= item.wakeAt then
            table.remove(Scheduler.waiting, i)
            table.insert(Scheduler.tasks, { co = item.co, args = {} })
        end
    end

    -- 2. Execute ready tasks
    local currentTasks = Scheduler.tasks
    Scheduler.tasks = {}

    for _, item in ipairs(currentTasks) do
        local success, action, param = coroutine.resume(item.co, table.unpack(item.args))

        if not success then
            print("Coroutine crashed: " .. tostring(action))
        elseif coroutine.status(item.co) ~= "dead" then
            if action == "SLEEP" then
                table.insert(Scheduler.waiting, { co = item.co, wakeAt = param })
            else
                -- Yielded without timer: re-queue immediately
                table.insert(Scheduler.tasks, { co = item.co, args = {} })
            end
        end
    end
end

Testing Parallel Execution

Scheduler.spawn(function()
    print("[Task A] Started")
    Scheduler.sleep(0.5)
    print("[Task A] Resumed after 500ms!")
end)

Scheduler.spawn(function()
    print("[Task B] Started")
    Scheduler.sleep(0.2)
    print("[Task B] Resumed after 200ms!")
end)

-- Simulate game engine frame updates
local start = os.clock()
while os.clock() - start < 1.0 do
    Scheduler.tick()
end

Exercises

  1. Extend the task scheduler to support an await(promise) pattern where a coroutine pauses until another task completes.
  2. Implement a cancellation token mechanism allowing cancellation of pending waiting coroutines.
  3. Explain why coroutines prevent race conditions and eliminate the need for mutex locks in single-threaded Lua.