79302215

Date: 2024-12-23 05:22:43
Score: 1.5
Natty:
Report link

An update on @Crowman 's answer:

package utils

import "sync"

type KeyedMutex struct {
    mutexes sync.Map // Zero value is empty and ready for use
}

func (m *KeyedMutex) Lock(key string) func() {
    value, _ := m.mutexes.LoadOrStore(key, &sync.Mutex{})
    mtx := value.(*sync.Mutex)
    mtx.Lock()

    return func() {
        mtx.Unlock()
        m.mutexes.Delete(key)
    }
}

func NewLock() KeyedMutex {
    return KeyedMutex{}
}

just adding a key-removing code, hope it will be helpful.

Reasons:
  • Has code block (-0.5):
  • User mentioned (1): @Crowman
  • Low reputation (1):
Posted by: user27745807