calog/examples/scripts/libraries/taskCooperative.lua

21 lines
1,023 B
Lua

-- Cooperative task shutdown with taskActive().
-- taskClose() is cooperative: it flips the task's shutdown flag and waits for the thread to
-- exit. A task busy in its own loop won't notice unless it polls taskActive(), so a
-- long-running worker checks it each iteration and breaks out when asked to stop.
-- run: bin/calog examples/scripts/libraries/taskCooperative.lua
local worker = taskSpawn("lua", [[
local ticks = 0
while taskActive() do -- false once the owner calls taskClose()
ticks = ticks + 1
timeSleep(25)
end
kvSet("workerTicks", ticks) -- runs after the loop breaks, before the thread exits
]])
calogPrint("owner: worker spawned, taskActive(handle) =", tostring(taskActive(worker)))
timeSleep(150) -- let it work for a bit
calogPrint("owner: asking the worker to stop")
taskClose(worker) -- returns as soon as the worker breaks its loop
calogPrint("owner: worker stopped after", kvGet("workerTicks"), "ticks")
calogExit(0)