# frozen_string_literal: true
require "tmpdir"

dir = Dir.mktmpdir
TRIES = 300

1.upto(TRIES) do |try|
  $stderr.puts "try #{try} of #{TRIES}"
  str = Ractor.make_shareable(Random.bytes(512 * 1024))
  # Control: one prior write from a single Ractor prevents the crash.
  File.binwrite(File.join(dir, "first"), str) if ENV["WRITE_FIRST"]

  go = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 0.02
  12.times.map do |n|
    Ractor.new(str, File.join(dir, "w#{n}"), go) do |s, path, at|
      Thread.pass until Process.clock_gettime(Process::CLOCK_MONOTONIC) >= at # start together
      File.binwrite(path, s)
    end
  end.each(&:join)

  GC.start
end

puts "finished #{TRIES} tries without crashing"
