Skip to content

Commit

Permalink
Fix case when released more then acquired.
Browse files Browse the repository at this point in the history
  • Loading branch information
marusama committed Dec 14, 2017
1 parent 04c7e8f commit 565ffd8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 13 additions & 1 deletion semaphore.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,25 @@ func (s *semaphore) TryAcquire(n int) bool {
}

for {
// get current semaphore count and limit
state := atomic.LoadUint64(&s.state)
count := state & 0xFFFFFFFF
limit := state >> 32

// new count
newCount := count + uint64(n)

if newCount <= limit {
if atomic.CompareAndSwapUint64(&s.state, state, limit<<32+newCount) {
// acquired
return true
}

// CAS failed, try again
continue
}

// semaphore is full
return false
}
}
Expand All @@ -159,13 +165,18 @@ func (s *semaphore) Release(n int) int {
panic("n must be positive number")
}
for {
// get current semaphore count and limit
state := atomic.LoadUint64(&s.state)
count := state & 0xFFFFFFFF
limit := state >> 32
if count == 0 {

if count < uint64(n) {
panic("semaphore release without acquire")
}

// new count
newCount := count - uint64(n)

if atomic.CompareAndSwapUint64(&s.state, state, state&0xFFFFFFFF00000000+newCount) {

// notifying possible waiters only if there weren't free slots before
Expand All @@ -179,6 +190,7 @@ func (s *semaphore) Release(n int) int {
// send broadcast signal
close(oldBroadcastCh)
}

return int(count)
}
}
Expand Down
12 changes: 12 additions & 0 deletions semaphore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,18 @@ func TestSemaphore_Release_without_Acquire_panic_expected(t *testing.T) {
sem.Release(1)
}

func TestSemaphore_Release_more_than_Acquired_panic_expected(t *testing.T) {
sem := New(1)

defer func() {
if recover() == nil {
t.Error("Panic expected")
}
}()
sem.Acquire(context.Background(), 1)
sem.Release(2)
}

func TestSemaphore_Acquire_2_times_Release_2_times(t *testing.T) {
sem := New(2)
checkLimitAndCount(t, sem, 2, 0)
Expand Down

0 comments on commit 565ffd8

Please sign in to comment.