require 'async'
require 'slow_op'

counts = Hash.new(0)
Fiber.set_scheduler(Async::Scheduler.new(worker_pool: IO::Event::WorkerPool.new(maximum_worker_count: 4)))
Async do |top|
  300.times do
    tasks = Array.new(4) do
      task = top.async do
        SlowOp.run(20)
      ensure
        counts[:ensure] += 1
        if ENV['FIRST'] == 'exist'
          counts[:exist_true_for_missing_path] += 1 if File.exist?('/nonexistent/path')
        else
          counts[:slow_op_did_not_run] += 1 unless SlowOp.run(1)
        end
      end
      top.async do
        sleep(0.0195 + (rand * 0.002))
        task.stop
      end
      task
    end
    tasks.each(&:wait)
  end
end
Fiber.set_scheduler(nil)
p counts
