var mutex sync.Mutex
func main() {
handle()
go register()
}
func register(){
myObject.OnEvent().DoFunc(HandleConnect)
}
func HandleConnect(){
handle()
}
func handle() bool {
mutex = sync.Mutex{}
mutex.Lock()
defer mutex.Unlock()
....some logic.... do login...
return true
}
I have a HandleConnect that is called many times in my application I want to lock the handle because if there are many calls I want that only one will do the logic of the login When I run it I got an error fatal error: sync: unlock of unlocked mutex
How I can solve it ?
You have a race condition in your code. You're using a global variable (which is fine, as far as it goes), but then you're constantly resetting the mutex variable:
func handle() bool {
mutex = sync.Mutex{} // Here you are re-initializing the mutex every time
mutex.Lock()
defer mutex.Unlock()
....some logic.... do login...
return true
}
Instead, simply don't reset the variable:
func handle() bool {
mutex.Lock()
defer mutex.Unlock()
....some logic.... do login...
return true
}
To visualize the problem, imagine you have a single goroutine going through these steps:
mutex = sync.Mutex{}
mutex.Lock()
...some logic....
defer mutex.Unlock()
All is fine.
But now imagine you have two groutines, A and B simultaneously running:
mutex = sync.Mutex{}
mutex.Lock()
mutex = sync.Mutex{}
NOTE: The mutex is now unlocked for all goroutines, because it's a global variable!!