Reading from file without locking it

后端 未结 2 1204
耶瑟儿~
耶瑟儿~ 2021-01-15 09:39

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 cons

2条回答
  •  遥遥无期
    2021-01-15 10:32

    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.
    }
    

提交回复
热议问题