我尝试Lock()
文件以从另一个进程中读取,所以我尝试以另一种方式进行操作:
var (
mutex = sync.Mutex{}
)
func main() {
fmt.Println("Start")
go runZiper()
mutex.Lock()
defer mutex.Unlock()
f2, _ := os.Open("test_tmp.txt")
// here will be writing to file
time.Sleep(3 * time.Second) //just for try
f2.Close()
}
func runZiper() { // this process will compress file (files) in some period
time.Sleep(1 * time.Second) //just for try
f, err := os.Create("test_tmp.txt.zip")
if err != nil { ... }
defer f.Close()
w := zip.NewWriter(f)
data, err := ioutil.ReadFile("test_tmp.txt")
if err != nil { ... }
fz, _ := w.Create("zipped.txt")
fz.Write(data)
w.Close()
}
但是我的compressor
(功能runZip
)仍然可以读取和压缩打开的文件。这样我就可以丢失信息。
如何避免这种情况?
我尝试使用sync.Mutex
和sync.RWMutex
,但结果相同。
答案 0 :(得分:2)
我认为有解决此问题的聪明方法。当您关闭该文件时,可以更改该文件的名称。另一方面,我们使用压缩器读取另一个名称,例如test_tmp1.txt。
let motionNavController = AppNavigationController(rootViewController: galleryViewController)
motionNavController.motionNavigationTransitionType = .none
motionNavController.isNavigationBarHidden = true
self.present(motionNavController, animated: true, completion: nil)