Vibescript Showcase
Staged barrier
Spawn a batch of tasks, hold at an explicit tasks.wait barrier, then aggregate the results in order.
Source
showcase/concurrency/staged_barrier.vibe
# title: Staged barrier
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Spawn a batch of tasks, hold at an explicit tasks.wait barrier, then aggregate the results in order.
# description: tasks.wait is an explicit barrier inside a Tasks.run scope. Use it when later code in the same block must wait for all spawned work so far before continuing — here we wait for every segment, then read the handle values and total them.
# tags: concurrency, tasks, structured-concurrency, barrier
# vibe: 0.4
def warm_segment(segment)
segment[:base] * segment[:multiplier]
end
def aggregate_segments(segments)
Tasks.run(max: 4) do |tasks|
handles = []
segments.each do |segment|
handles = handles.push(tasks.spawn(:warm_segment, segment))
end
tasks.wait
totals = handles.map do |handle|
handle.value
end
{
segments: totals,
total: totals.sum
}
end
end
def run
aggregate_segments([
{ base: 10, multiplier: 2 },
{ base: 5, multiplier: 4 },
{ base: 8, multiplier: 3 }
])
end
Output
Press run to execute run from this example.