123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- package xugu
- import (
- "sync"
- "time"
- )
- type Sema struct {
- mutex sync.Mutex
- cond *sync.Cond
- count int
- }
- func initSema() *Sema {
- sema := &Sema{}
- sema.cond = sync.NewCond(&sema.mutex)
- return sema
- }
- func initSemaN(n int) *Sema {
- sema := &Sema{count: n}
- sema.cond = sync.NewCond(&sema.mutex)
- return sema
- }
- func (s *Sema) decSema() {
- s.mutex.Lock()
- for s.count == 0 {
- s.cond.Wait()
- }
- s.count--
- s.mutex.Unlock()
- }
- func (s *Sema) incSema() {
- s.mutex.Lock()
- s.count++
- s.cond.Signal()
- s.mutex.Unlock()
- }
- func (s *Sema) waitSema() {
- s.decSema()
- }
- func (s *Sema) waitSemaT(timeout time.Duration) bool {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- timer := time.NewTimer(timeout)
- defer timer.Stop()
- for s.count == 0 {
- timer.Reset(timeout)
- select {
- case <-timer.C:
- return false
- case <-func() chan struct{} {
- ch := make(chan struct{})
- go func() {
- s.cond.Wait()
- close(ch)
- }()
- return ch
- }():
- }
- }
- s.count--
- return true
- }
- func (s *Sema) clrSema() {
- s.mutex.Lock()
- for s.count > 0 {
- s.count--
- }
- s.mutex.Unlock()
- }
- func (s *Sema) closeSema() {
-
- }
- func sleep(t int) {
- time.Sleep(time.Duration(t) * time.Millisecond)
- }
|