From f39a916e5fc4d6ed6a1290723d5946f6fff84485 Mon Sep 17 00:00:00 2001 From: Zachary Yedidia Date: Sun, 4 Aug 2019 14:32:42 -0700 Subject: [PATCH] Fix minor autosave race condition --- internal/action/command.go | 3 ++- internal/config/autosave.go | 31 +++++++++++++++++++++++-------- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/internal/action/command.go b/internal/action/command.go index a062a23d..029f9582 100644 --- a/internal/action/command.go +++ b/internal/action/command.go @@ -406,9 +406,10 @@ func SetGlobalOptionNative(option string, nativeValue interface{}) error { } } else if option == "autosave" { if nativeValue.(float64) > 0 { + config.SetAutoTime(int(nativeValue.(float64))) config.StartAutoSave() } else { - config.StopAutoSave() + config.SetAutoTime(0) } } else { for _, pl := range config.Plugins { diff --git a/internal/config/autosave.go b/internal/config/autosave.go index 2c5bf815..db473081 100644 --- a/internal/config/autosave.go +++ b/internal/config/autosave.go @@ -1,30 +1,45 @@ package config import ( - "log" + "sync" "time" ) var Autosave chan bool +var autotime int + +// lock for autosave +var autolock sync.Mutex func init() { Autosave = make(chan bool) } +func SetAutoTime(a int) { + autolock.Lock() + autotime = a + autolock.Unlock() +} + +func GetAutoTime() int { + autolock.Lock() + a := autotime + autolock.Unlock() + return a +} + func StartAutoSave() { go func() { for { - autotime := time.Duration(GlobalSettings["autosave"].(float64)) if autotime < 1 { break } - time.Sleep(autotime * time.Second) - log.Println("Autosave") + time.Sleep(time.Duration(autotime) * time.Second) + // it's possible autotime was changed while sleeping + if autotime < 1 { + break + } Autosave <- true } }() } - -func StopAutoSave() { - GlobalSettings["autosave"] = float64(0) -}