Ruby File.write (filename, text) 是否线程安全?

linjunhalida · 2015年04月19日 · 最后由 gihnius 回复于 2015年04月20日 · 2577 次阅读

请教一下大家,如果好几个进程同时调用 File.write(filename, text) ,是否会出现冲突?File.write 在写之前是否会锁文件?

貌似 ruby 内置的类都不是 thread safe 的,IO, File 应该更不是。

the GIL did, in fact, make MRI's native C method implementations atomic

MRI 原生的 C 语言编写的函数都是线程安全的。参考原文

File.write的实现是 C 函数rb_io_s_write, 因此,File.write应该是线程安全的。

不是很了解 GIL,没有找到明确的说明,但愿是线程安全的。

刚翻了下,rails 有实现 File.atomic_write here,ruby 2.2 的 logger 依然用 Mutex:


def write(message)
  begin
    @mutex.synchronize do
      if @shift_age and @dev.respond_to?(:stat)
        begin
          check_shift_log
        rescue
          warn("log shifting failed. #{$!}")
        end
      end
      begin
        @dev.write(message)
      rescue
        warn("log writing failed. #{$!}")
      end
    end
  rescue Exception => ignored
    warn("log writing failed. #{ignored}")
  end
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号