从文件中读取而不锁定它 [英] Reading from file without locking it

查看:192
本文介绍了从文件中读取而不锁定它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次请求进来的时候,我都会不断地向一个文件写入一些数据。我也想解析这个文件并且有时候读取它。如果文件不断被写入,我怎样才能做到这一点?什么是模式?

解决方案

您可以使用 sync.RWMutex 。然后:


  • 当您需要读取文件时,请调用 RLock(),读取,然后调用 RUnlock()

  • 当需要写入文件时,调用 Lock ),然后调用 Unlock()


    只要你这样做,你就可以确保:


    • 任何时候只有一个goroutine会写入文件。
    • 如果您在修改文件时尝试读取该文件,则锁定将等到您完成写入操作才开始读取文件。 如果您在读取文件时尝试写入该文件,则该锁将等待您完成读取,然后再开始写入。



    一个非常小的例子:

     包示例

    导入(
    sync

    $ b var fileMutex = new(sync.RWMutex)

    func readFile(){
    fileMutex.RLock()
    推迟fileMutex.RUnlock ()

    //读取文件不要修改它。

    $ b $ func writeFile(){
    fileMutex.Lock()
    推迟fileMutex.Unlock()

    //写入文件。
    }


    I constantly write to one file some data everytime requests come in. I also want to parse this file and read from it sometimes. How can I do this reading if the file is constantly being written to? What's the pattern?

    解决方案

    You could make use of sync.RWMutex. Then:

    • When you need to read the file, call RLock(), read, then call RUnlock().
    • When you need to write to the file, call Lock(), write, then call Unlock().

    As long as you do that, you're ensuring that:

    • Only one goroutine will be writing to the file at any time.
    • If you try to read the file while it's being modified, the lock will wait until you finish writing before starting to read the file.
    • If you try to write to the file while it's being read, the lock will wait until you finish reading before starting to write.

    Here's a very little example:

    package sample
    
    import (
        "sync"
    )
    
    var fileMutex = new(sync.RWMutex)
    
    func readFile() {
        fileMutex.RLock()
        defer fileMutex.RUnlock()
    
        // Read the file. Don't modify it.
    }
    
    func writeFile() {
        fileMutex.Lock()
        defer fileMutex.Unlock()
    
        // Write to the file.
    }
    

    这篇关于从文件中读取而不锁定它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆