Search code examples
rubyfile-iobackground-process

Can I write to a file in background?


During the execution of my script I need to write a big file to disk to store partial calculations. This file is quite big and it is not needed for the rest of the script. At the moment I need to wait for the writing to finish before I can continue the execution of the script.

Is there a way to write the file in background? Something like launching a separate process for writing while the rest of the script continues undisturbed?


Solution

  • thread = Thread.new do
      File.open("output.txt", "w") do |file|
        file.puts "hello from the background"
      end
    end
    
    # Finish the script
    ...
    
    # Wait for the file writing to finish
    thread.join