use a named lock instead of a single per-pool mutex.

This commit is contained in:
fiatjaf 2023-08-06 19:54:30 -03:00
parent 2e9cdc8255
commit b522d24c30
No known key found for this signature in database
GPG Key ID: BAD43C4BE5C1A3A1
2 changed files with 13 additions and 3 deletions

View File

@ -13,7 +13,6 @@ type SimplePool struct {
Relays map[string]*Relay Relays map[string]*Relay
Context context.Context Context context.Context
mutex sync.Mutex
cancel context.CancelFunc cancel context.CancelFunc
} }
@ -31,8 +30,7 @@ func NewSimplePool(ctx context.Context) *SimplePool {
func (pool *SimplePool) EnsureRelay(url string) (*Relay, error) { func (pool *SimplePool) EnsureRelay(url string) (*Relay, error) {
nm := NormalizeURL(url) nm := NormalizeURL(url)
pool.mutex.Lock() defer namedLock(url)()
defer pool.mutex.Unlock()
relay, ok := pool.Relays[nm] relay, ok := pool.Relays[nm]
if ok && relay.IsConnected() { if ok && relay.IsConnected() {

View File

@ -3,10 +3,22 @@ package nostr
import ( import (
"net/url" "net/url"
"strings" "strings"
"sync"
"github.com/dgraph-io/ristretto/z"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
) )
const MAX_LOCKS = 50
var namedMutexPool = make([]sync.Mutex, MAX_LOCKS)
func namedLock(name string) (unlock func()) {
idx := z.MemHashString(name) % MAX_LOCKS
namedMutexPool[idx].Lock()
return namedMutexPool[idx].Unlock
}
func similar[E constraints.Ordered](as, bs []E) bool { func similar[E constraints.Ordered](as, bs []E) bool {
if len(as) != len(bs) { if len(as) != len(bs) {
return false return false