Skip to content

Instantly share code, notes, and snippets.

@liwh
Created February 15, 2011 02:36
Show Gist options
  • Select an option

  • Save liwh/827008 to your computer and use it in GitHub Desktop.

Select an option

Save liwh/827008 to your computer and use it in GitHub Desktop.
线程安全的文件读写 线程安全的文件读写
原子写文件:
当有一个线程对文件进行写的操作的时候,而此时,有其他多个线程对这个文件进行读的操作的时候,如果以见得方式对文件进行写操作的时候.这时,就会造成某些线程会看到不完成的文件.
所以,我们可以利用原子方法automic_write.首先,我们将写的文件存在一个临时文件中,然后,再将临时文件去覆盖我们需要对那个进行写操作的文件.
require 'fileutils'
def atomic_write(path, temp_path, content)
File.open(temp_path, 'w+') do |f|
f.write(content)
end
FileUtils.mv(temp_path, path)
rails里的方法实现:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/file/atomic.rb
锁文件:
还有一种情况,当多个线程对文件进行写操作的时候,这是,我们就不能让他们同时进行写操作了,我们得给文件进行枷锁,保证同一时间只有一个线程对文件进行写操作,类似,java里的synchronism.在ruby里解决方式,就是利用locks,在ruby里提供flock变量方法.
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('my_file') do
atomic_write('my_file', 'my_file.tmp', 'Hello, World!')
end
在rails里面也提供了一种很好的实现.https://github.com/rails/rails/blob/master/activesupport/lib/active_support/cache/file_store.rb#L121
http://douglasfshearer.com/blog/threadsafe-file-consistency-in-ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment