Fix minor autosave race condition

This commit is contained in:
Zachary Yedidia 2019-08-04 14:32:42 -07:00
parent c0293b5d0e
commit f39a916e5f
2 changed files with 25 additions and 9 deletions

View file

@ -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 {

View file

@ -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)
}