New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Concurrency-safe way to use viper.WatchConfig()? #378
Comments
Yes, there is indeed a data race as I just encountered. Take this for example:
Race condition on the data read of that value intermittently. So sometimes a value such as: |
The function registered with OnConfigChange is called in the goroutine of the WatchConfig function event loop and this is a separate goroutine from the one you are using to call viper. You should not access the viper instance from this registered function as far as viper is not safe for concurrent use. You should use an external mutex to synchronize you with yourself when you use your viper instance if you want to do that. package main
import (
"sync"
"time"
"github.com/spf13/viper"
"github.com/fsnotify/fsnotify"
)
var viperLock sync.Mutex
func main() {
viperLock.Lock()
viper.OnConfigChange(func(in fsnotify.Event) {
viperLock.Lock()
viper.Set("delay", "10s")
viperLock.Unlock()
})
viperLock.Unlock()
viperLock.Lock()
viper.Set("delay", "30s")
viperLock.Unlock()
// ...
viperLock.Lock()
d := viper.GetDuration("delay")
viperLock.Unlock()
time.Sleep(d)
} |
As I understand it, it's not
The |
Hello, i'm make changes to safe concurrency and work for me |
I am have the same problem. in file viper.go, at line 390: |
@sagikazarmark thoughts? |
This is a race condition to assign |
there are multiple issues for this race condition in watchConfig. Seems that none cares about the issue |
viper.WatchConfig() store the changed config without any synchronization. Won't it cause data race if there are concurrent config reads in other threads/goroutines?
The text was updated successfully, but these errors were encountered: