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.
You can write to file in a thread-safe manner using a mutex lock via the threading. Lock class.
File is not thread safe. However, the java API for this class doesn't say anything about its thread safety.
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.
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.
You could give a lock by File#flock
File.open("myfile", 'a') { |f|
f.flock(File::LOCK_EX)
f.puts("#{sometext}")
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With