ceremonyclient/go-libp2p-kad-dht/internal/ctx_mutex.go
2024-10-12 11:55:17 -07:00

29 lines
359 B
Go

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")
}
}