Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making write to a file thread safe

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, making file write such as the above not thread safe. Does anyone have any idea how to make this file write thread safe in the simplest way?

More Info: If it matters, I am using the rspec framework.

like image 643
user1788294 Avatar asked Apr 28 '14 06:04

user1788294


People also ask

Is writing to file thread-safe?

You can write to file in a thread-safe manner using a mutex lock via the threading. Lock class.

Is files write thread-safe Java?

File is not thread safe. However, the java API for this class doesn't say anything about its thread safety.

Can two threads write to the same file?

You can have multiple threads write to the same file - but one at a time. All threads will need to enter a synchronized block before writing to the file. In the P2P example - one way to implement it is to find the size of the file and create a empty file of that size.

Is read and write thread-safe?

It's safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it's safe when A is being written in thread 1 and B is being read in thread 2.


2 Answers

You could give a lock by File#flock

File.open("myfile", 'a') { |f| 
  f.flock(File::LOCK_EX)
  f.puts("#{sometext}") 
}
like image 194
xdazz Avatar answered Sep 22 '22 03:09

xdazz


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
like image 25
SreekanthGS Avatar answered Sep 18 '22 03:09

SreekanthGS