Read and write file atomically

前端 未结 2 1853
一向
一向 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:02

    Take a look at transaction and open_and_lock_file methods in "pstore.rb" (Ruby stdlib).

    YAML::Store works fine for me. So when I need to read/write atomically I (ab)use it to store data as a Hash.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题