Support spawning new parallel functions (#2263)

- Split implementation of `parallel.waitFor{All,Any}` up. Their
   implementations are now sufficiently complicated it doesn't make
   sense to share the core.

 - Support spawning new functions from within `parallel.waitForAll`.

 - Flesh out the `parallel.waitForAll` docs a little.
This commit is contained in:
Ruby H authored and GitHub committed 2026-05-26 14:13:07 +00:00
1 parent 3e7ce15ba6
commit 15a5e776cb
3 files changed
+232 -71

No files matched your search

@@ -39,63 +39,15 @@ the other.
@since 1.2
]]
local exception = dofile("rom/modules/main/cc/internal/tiny_require.lua")("cc.internal.exception")
local function create(...)
local barrier_ctx = { co = coroutine.running() }
local functions = table.pack(...)
local threads = {}
for i = 1, functions.n, 1 do
local fn = functions[i]
if type(fn) ~= "function" then
error("bad argument #" .. i .. " (function expected, got " .. type(fn) .. ")", 3)
end
threads[i] = { co = coroutine.create(function() return exception.try_barrier(barrier_ctx, fn) end), filter = nil }
end
return threads
end
local function runUntilLimit(threads, limit)
local count = #threads
if count < 1 then return 0 end
local living = count
local event = { n = 0 }
while true do
for i = 1, count do
local thread = threads[i]
if thread and (thread.filter == nil or thread.filter == event[1] or event[1] == "terminate") then
local ok, param = coroutine.resume(thread.co, table.unpack(event, 1, event.n))
if ok then
thread.filter = param
elseif type(param) == "string" and exception.can_wrap_errors() then
error(exception.make_exception(param, thread.co))
else
error(param, 0)
end
if coroutine.status(thread.co) == "dead" then
threads[i] = false
living = living - 1
if living <= limit then
return i
end
end
end
end
event = table.pack(os.pullEventRaw())
end
end
local require = dofile("rom/modules/main/cc/internal/tiny_require.lua")
local expect = require("cc.expect").expect
local exception = require("cc.internal.exception")
--[[- Switches between execution of the functions, until any of them
finishes. If any of the functions errors, the message is propagated upwards
from the [`parallel.waitForAny`] call.
@tparam function ... The functions this task will run
@tparam function ... The functions to run in parallel.
@usage Print a message every second until the `q` key is pressed.
local function tick()
@@ -115,15 +67,77 @@ from the [`parallel.waitForAny`] call.
print("Everything done!")
]]
function waitForAny(...)
local threads = create(...)
return runUntilLimit(threads, #threads - 1)
local barrier_ctx = { co = coroutine.running() }
local functions = table.pack(...)
local threads = {}
for i = 1, functions.n do
local fn = functions[i]
expect(i, fn, "function")
threads[i] = {
co = coroutine.create(function() return exception.try_barrier(barrier_ctx, fn) end),
filter = nil,
}
end
local count = functions.n
if count < 1 then return 0 end
local event = { n = 0 }
while true do
for i = 1, count do
local thread = threads[i]
if thread.filter == nil or thread.filter == event[1] or event[1] == "terminate" then
local ok, param = coroutine.resume(thread.co, table.unpack(event, 1, event.n))
if not ok then
error(exception.wrap_error(param, thread.co), 0)
end
-- Abort if this coroutine has finished
if coroutine.status(thread.co) == "dead" then return i end
thread.filter = param
end
end
event = table.pack(os.pullEventRaw())
end
end
--[[- Switches between execution of the functions, until all of them are
finished. If any of the functions errors, the message is propagated upwards
from the [`parallel.waitForAll`] call.
--[[-
Runs several functions in parallel, until all of them are finished.
If any of the functions errors, the other functions are not resumed, and the
error is propagated upwards.
> [!WARNING]
>
> While any number of functions can be run in parallel, running too many things
> in parallel can sometimes cause issues:
>
> - Computers only buffer 256 events at a time. Trying to run several hundred
> functions in parallel (particularly when calling peripheral methods) can
> cause the event queue to fill up, resulting in events being dropped, and
> programs getting stuck.
> - Computers only run 16 HTTP requests at a time. Trying to run more than that
> in parallel will have no effect.
### Spawning new parallel functions
In some cases, you may want to start running additional functions in parallel
from an existing [`parallel.waitForAll`] call. Every function passed to
[`waitForAll`] can accept a `spawn` argument, which can be called to spawn new
parallel functions.
```lua
parallel.waitForAll(function(spawn)
spawn(function() sleep(1); print("Finished 1") end)
spawn(function() sleep(2); print("Finished 2") end)
end)
```
@tparam function(spawn: function(fn: function, any...)) ... The functions to run
in parallel.
@tparam function ... The functions this task will run
@usage Start off two timers and wait for them both to run.
local function a()
@@ -137,8 +151,100 @@ from the [`parallel.waitForAll`] call.
parallel.waitForAll(a, b)
print("Everything done!")
@usage Generate a list of functions to run in parallel.
local funcs = {}
for i = 1, 5 do
table.insert(funcs, function()
sleep(math.random())
print("Finished " .. i)
end)
end
parallel.waitForAll(table.unpack(funcs))
print("Everything done!")
@usage Run new functions in parallel from within `waitForAll`.
parallel.waitForAll(function(spawn)
for i = 1, 5 do
spawn(function()
sleep(math.random())
print("Finished " .. i)
end)
end
end)
print("Everything done!")
@changed 1.120.0 Added ability to spawn new parallel functions.
]]
function waitForAll(...)
local threads = create(...)
return runUntilLimit(threads, 0)
local barrier_ctx = { co = coroutine.running() }
local can_spawn, threads, count = false, {}, 0
local function spawn(fn, ...)
expect(1, fn, "function")
if not can_spawn then error("Cannot spawn new functions outside of waitForAll", 2) end
threads[count + 1] = {
co = coroutine.create(function(...) return exception.try_barrier(barrier_ctx, fn, ...) end),
filter = nil,
resume_with = table.pack(...),
}
count = count + 1
end
local functions = table.pack(...)
can_spawn = true
for i = 1, functions.n, 1 do
local fn = functions[i]
expect(i, fn, "function")
spawn(fn, spawn)
end
can_spawn = false
local event = { n = 0 }
while true do
local i = 1
while i <= count do
local thread = threads[i]
-- If this is a new coroutine, start it with the "resume_with" data,
-- otherwise resume it with the event (if it matches).
local resume_with
if thread.resume_with then
resume_with = thread.resume_with
thread.resume_with = nil
elseif thread.filter == nil or thread.filter == event[1] or event[1] == "terminate" then
resume_with = event
end
if resume_with then
can_spawn = true
local ok, param = coroutine.resume(thread.co, table.unpack(resume_with, 1, resume_with.n))
can_spawn = false
if not ok then
error(exception.wrap_error(param, thread.co), 0)
end
if coroutine.status(thread.co) == "dead" then
-- If this thread has died, remove it and repeat this
-- iteration.
table.remove(threads, i)
i, count = i - 1, count - 1
end
thread.filter = param
end
i = i + 1
end
if count == 0 then return end
event = table.pack(os.pullEventRaw())
end
end
@@ -144,6 +144,20 @@ local function can_wrap_errors(thread)
return false
end
--[[- Wrap an error into an exception, when it is safe to do so.
@param err The error to wrap.
@tparam coroutine thread The coroutine the error occurred on.
@return The constructed exception, or the original error.
]]
local function wrap_error(err, thread)
if type(err) == "string" and can_wrap_errors() then
return make_exception(err, thread)
else
return err
end
end
--[[- Attempt to call the provided function `func` with the provided arguments.
@tparam function func The function to call.
@@ -244,6 +258,7 @@ end
return {
make_exception = make_exception,
wrap_error = wrap_error,
try_barrier = try_barrier,
can_wrap_errors = can_wrap_errors,
@@ -33,10 +33,12 @@ describe("The parallel library", function()
it("accepts an arbitrary number of functions", function()
local count = 0
local fns = {}
for i = 1, 50 do fns[i] = function()
count = count + 1
coroutine.yield()
end end
for i = 1, 50 do
fns[i] = function()
count = count + 1
coroutine.yield()
end
end
os.queueEvent("dummy")
parallel.waitForAny(table.unpack(fns))
expect(count):eq(50)
@@ -79,25 +81,63 @@ describe("The parallel library", function()
local function a()
entries[#entries + 1] = "first"
local s = coroutine.yield()
entries[#entries + 1] = s
entries[#entries + 1] = "a: " .. s
end
local function b()
entries[#entries + 1] = "second"
local s = coroutine.yield()
entries[#entries + 1] = s
entries[#entries + 1] = "b: " .. s
end
os.queueEvent("yield")
parallel.waitForAll(a, b)
expect(entries):same({ "first", "second", "yield", "yield" })
expect(entries):same({ "first", "second", "a: yield", "b: yield" })
end)
it("can spawn new functions", function()
local entries = {}
local function a(name)
entries[#entries + 1] = name
local s = coroutine.yield()
entries[#entries + 1] = name .. ": " .. s
end
local function b(spawn)
entries[#entries + 1] = "b"
spawn(a, "a1")
spawn(a, "a2")
local s = coroutine.yield()
entries[#entries + 1] = "b: " .. s
spawn(a, "a3")
end
os.queueEvent("yield")
os.queueEvent("yield")
parallel.waitForAll(b)
expect(entries):same({
"b",
"a1",
"a2",
"b: yield",
"a1: yield",
"a2: yield",
"a3",
"a3: yield",
})
end)
it("cannot spawn outside of parallel", function()
local spawn
parallel.waitForAll(function(s) spawn = s end)
expect.error(spawn, function() end):eq("Cannot spawn new functions outside of waitForAll")
end)
it("accepts an arbitrary number of functions", function()
local count = 0
local fns = {}
for i = 1, 50 do fns[i] = function()
count = count + 1
coroutine.yield()
end end
for i = 1, 50 do
fns[i] = function()
count = count + 1
coroutine.yield()
end
end
os.queueEvent("dummy")
parallel.waitForAll(table.unpack(fns))
expect(count):eq(50)