You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby线程写入文件:数据仅在程序终止后可见的问题求助

问题解决:实时写入文件内容

你的问题出在Ruby的文件I/O缓冲机制上——默认情况下,Ruby会把写入的数据暂存在内存缓冲区里,只有当缓冲区被填满、文件被关闭,或者程序终止时,才会把缓冲区里的内容一次性写入磁盘,所以你在程序运行期间看不到文件里的新内容。

下面给你几种解决办法:

方法1:每次写入后手动刷新缓冲区

在每次写入操作完成后,调用flush方法强制把缓冲区内容刷到磁盘:

price_file = File.open(price_file, "w+")

$time = Thread.new { 
    while true
        price = Api.new.api(nil)

        price_file << price
        price_file << " "
        price_file.flush  # 新增该行,强制刷新缓冲区
       
        puts price

        sleep(seconds)
    end
}

方法2:打开文件时启用同步模式

打开文件时指定sync: true参数,这样所有写入操作都会直接同步到磁盘,不需要手动调用flush:

# 打开文件时开启同步模式
price_file = File.open(price_file, "w+", sync: true)

$time = Thread.new { 
    while true
        price = Api.new.api(nil)

        price_file << price
        price_file << " "
       
        puts price

        sleep(seconds)
    end
}

方法3:使用fsync彻底刷到物理磁盘

如果需要确保数据真的写入物理磁盘(比如防止系统崩溃丢失数据),可以用fsync方法,它会等待操作系统把数据写入磁盘后才返回:

price_file = File.open(price_file, "w+")

$time = Thread.new { 
    while true
        price = Api.new.api(nil)

        price_file << price
        price_file << " "
        price_file.fsync  # 强制刷到物理磁盘
       
        puts price

        sleep(seconds)
    end
}

注意:fsync比flush的性能开销更大,如果你只是需要在程序运行时能看到文件内容,用前两种方法就足够了。

内容的提问来源于stack exchange,提问作者seamus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:32:38