#---
# Excerpted from "Programming Ruby 3.2",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit https://pragprog.com/titles/ruby6 for more book information.
#---
require "async"
require "async/barrier"
require "yaml"

barrier = Async::Barrier.new
Sync do
  results = []
  totals = Dir.children("./code/tut_threads/data").sort.map do |name|
    barrier.async do
      count = Integer(name.split("_").last.split(".").first)
      puts "running #{name}, sleeping #{6 - count}"
      sleep(6 - count)
      data = YAML.safe_load_file("./code/tut_threads/data/#{name}")
      puts "loaded #{name}"
      results << Float(data["price"]) * Integer(data["in_stock"])
    end
  end

  barrier.wait
  puts results.sum
ensure
  barrier.stop
end
