Skip to content

Commit

Permalink
xsync: Add ContextMutex
Browse files Browse the repository at this point in the history
Tends to be extremely useful.
  • Loading branch information
nhooyr committed Mar 3, 2023
1 parent 23c72ab commit 6df14ff
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions xsync/xsync.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package xsync

type ContextMutex struct {
ch chan struct{}
}

func NewContextMutex() *ContextMutex {
return &ContextMutex{
ch: make(chan struct{}, 1),
}
}

func (cm *ContextMutex) TryLock() bool {
select {
case cm.ch <- struct{}{}:
return true
default:
return false
}
}

func (cm *ContextMutex) Lock(ctx context.Context) error {
select {
case <-ctx.Done():
return fmt.Errorf("failed to acquire lock: %w", ctx.Err())
case cm.ch <- struct{}{}:
return nil
}
}

func (cm *ContextMutex) Unlock() {
select {
case <-cm.ch:
default:
panic("xsync.ContextMutex: Unlock before Lock")
}
}

0 comments on commit 6df14ff

Please sign in to comment.