如何锁定功能? [关闭]

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:

  1. Reset the mutex. mutex = sync.Mutex{}
  2. Lock the mutex. mutex.Lock()
  3. Do stuff ...some logic....
  4. Release the lock. defer mutex.Unlock()

All is fine.

But now imagine you have two groutines, A and B simultaneously running:

  1. A resets the mutex: mutex = sync.Mutex{}
  2. A locks the mutex: mutex.Lock()
  3. A Do stuff
  4. B resets the mutex: mutex = sync.Mutex{} NOTE: The mutex is now unlocked for all goroutines, because it's a global variable!!
  5. A Unlock mutex, and crash, because it's already unlocked