Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ func (s *semaphore) Lock() {
s.ch <- struct{}{}
}

// Unlock releases semaphore, can block if nothing acquired before.
// Unlock releases semaphore. It panics if called without a matching Lock/TryLock,
// matching sync.Mutex rather than blocking forever on an empty channel.
func (s *semaphore) Unlock() {
<-s.ch
select {
case <-s.ch:
default:
panic("syncs: unlock of unlocked semaphore")
}
}

// TryLock acquires semaphore if possible, returns true if acquired, false otherwise.
Expand Down
15 changes: 15 additions & 0 deletions semaphore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,18 @@ func TestSemaphore_TryLock(t *testing.T) {
})
}
}

func TestSemaphore_UnlockUnlocked(t *testing.T) {
sema := NewSemaphore(1)
assert.PanicsWithValue(t, "syncs: unlock of unlocked semaphore", func() {
sema.Unlock()
})

sema.Lock()
assert.NotPanics(t, func() {
sema.Unlock()
})
assert.PanicsWithValue(t, "syncs: unlock of unlocked semaphore", func() {
sema.Unlock()
})
}