Read and write file atomically

前端 未结 2 1852
一向
一向 2021-01-12 20:24

I\'d like to read and write a file atomically in Ruby between multiple independent Ruby processes (not threads).

  • I found atomic_write from ActiveSupport. This
2条回答
  •  被撕碎了的回忆
    2021-01-12 21:10

    You want to use File#flock in exclusive mode. Here's a little demo. Run this in two different terminal windows.

    filename = 'test.txt'
    
    File.open(filename, File::RDWR) do |file|
      file.flock(File::LOCK_EX)
    
      puts "content: #{file.read}"
      puts 'doing some heavy-lifting now'
      sleep(10)
    end
    

提交回复
热议问题