ceremonyclient/go-libp2p-kad-dht/internal/ctx_mutex.go

29 lines
359 B
Go
Raw Normal View History

2024-10-12 18:48:25 +00:00
package internal
import (
"context"
)
type CtxMutex chan struct{}
func NewCtxMutex() CtxMutex {
return make(CtxMutex, 1)
}
func (m CtxMutex) Lock(ctx context.Context) error {
select {
case m <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (m CtxMutex) Unlock() {
select {
case <-m:
default:
panic("not locked")
}
}