如何锁定功能? [关闭]
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 ?
var Mutex sync.Mutex
func main(){
handle()
go register( )
}
func register(){
myObject.OnEvent()。DoFunc(HandleConnect)
}
func HandleConnect(){
handle()
}
func handle()bool {
互斥锁= sync.Mutex {}
互斥锁.Lock()
延迟互斥锁.Unlock()
....一些逻辑......登录...
返回true
}
code> pre>
我有一个在我的应用程序中被多次调用的HandleConnect
我想锁定该句柄,因为如果有很多调用,我希望只有一个能做到 登录名
当我运行它时,我遇到错误
致命错误:同步:解锁的互斥锁解锁 strong> p>
如何解决? p>
div>
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:
- Reset the mutex.
mutex = sync.Mutex{}
- Lock the mutex.
mutex.Lock()
- Do stuff
...some logic....
- Release the lock.
defer mutex.Unlock()
All is fine.
But now imagine you have two groutines, A and B simultaneously running:
-
A resets the mutex:
mutex = sync.Mutex{}
-
A locks the mutex:
mutex.Lock()
- A Do stuff
-
B resets the mutex:
mutex = sync.Mutex{}
NOTE: The mutex is now unlocked for all goroutines, because it's a global variable!! - A Unlock mutex, and crash, because it's already unlocked