Vibescript Showcase

Staged barrier

Start a batch of tasks, wait for all of them, then total the results.

Showcase
Source showcase/concurrency/staged_barrier.vibe
# title: Staged barrier
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Start a batch of tasks, wait for all of them, then total the results.
# description: tasks.wait pauses the current Tasks.run block until its active tasks finish.
# 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 example to run this code.