Metered concurrency: Difference between revisions

→‎Sync.Cond: simplify, meet documented requirements of sync.Cond
(→‎Sync.Cond: simplify, meet documented requirements of sync.Cond)
Line 668:
"os"
"sync"
"sync/atomic"
"time"
)
Line 675 ⟶ 674:
 
type countSem struct {
c int32int
cond *sync.Cond
}
 
func newCount(n int) *countSem {
return &countSem{int32(n), sync.NewCond(new(Cond{L: &sync.Mutex)){}}}
}
 
func (cs *countSem) count() int {
cs.cond.L.UnlockLock()
return int(atomic.LoadInt32(&cs.c))
c := cs.int
cs.L.Unlock()
return c
}
 
func (cs *countSem) acquire() {
cs.L.Lock()
if atomic.AddInt32(&cs.c, -1) < 0 {
atomic.AddInt32(&cs.c, 1)int--
for cs.int < 0 cs.cond.L.Lock(){
for atomiccs.AddInt32Wait(&cs.c, -1) < 0 {
atomic.AddInt32(&cs.c, 1)
cs.cond.Wait()
}
cs.cond.L.Unlock()
}
cs.L.Unlock()
}
 
func (cs *countSem) release() {
atomic.AddInt32(&cs.c, 1L.Lock()
cs.cond.Signal()int++
cs.L.Unlock()
cs.Broadcast()
}
 
Line 722 ⟶ 723:
studied.Done()
}</lang>
 
===Monitor===
Monitor-style solution implements counting semaphore as a monitor goroutine encapsulating the count. It implements semaphore operations with separate Go channels.
1,707

edits