Create a file entry

I have a function in a ruby ​​file that writes to a file like this

File.open("myfile", 'a') { |f| f.puts("#{sometext}") }

This function is called in different threads, which makes the file entry as shown above, not thread safe. Does anyone know how to make this file write-safe by stream in the simplest way?

Additional Information: If it matters, I use the rspec framework.

+4
source share
2 answers

You can give a lock File # flock

File.open("myfile", 'a') { |f| 
  f.flock(File::LOCK_EX)
  f.puts("#{sometext}") 
}
+8
source

Referring to: http://blog.douglasfshearer.com/post/17547062422/threadsafe-file-consistency-in-ruby

def lock(path)
  # We need to check the file exists before we lock it.
  if File.exist?(path)
    File.open(path).flock(File::LOCK_EX)
  end

  # Carry out the operations.
  yield

  # Unlock the file.
  File.open(path).flock(File::LOCK_UN)
end

lock("myfile") do
  File.open("myfile", 'a') { |f| f.puts("#{sometext}") }
end
+2
source

Source: https://habr.com/ru/post/1538348/


All Articles