github.com/lingyao2333/mo-zero@v1.4.1/core/syncx/cond.go (about)

     1  package syncx
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/lingyao2333/mo-zero/core/lang"
     7  	"github.com/lingyao2333/mo-zero/core/timex"
     8  )
     9  
    10  // A Cond is used to wait for conditions.
    11  type Cond struct {
    12  	signal chan lang.PlaceholderType
    13  }
    14  
    15  // NewCond returns a Cond.
    16  func NewCond() *Cond {
    17  	return &Cond{
    18  		signal: make(chan lang.PlaceholderType),
    19  	}
    20  }
    21  
    22  // WaitWithTimeout wait for signal return remain wait time or timed out.
    23  func (cond *Cond) WaitWithTimeout(timeout time.Duration) (time.Duration, bool) {
    24  	timer := time.NewTimer(timeout)
    25  	defer timer.Stop()
    26  
    27  	begin := timex.Now()
    28  	select {
    29  	case <-cond.signal:
    30  		elapsed := timex.Since(begin)
    31  		remainTimeout := timeout - elapsed
    32  		return remainTimeout, true
    33  	case <-timer.C:
    34  		return 0, false
    35  	}
    36  }
    37  
    38  // Wait waits for signals.
    39  func (cond *Cond) Wait() {
    40  	<-cond.signal
    41  }
    42  
    43  // Signal wakes one goroutine waiting on c, if there is any.
    44  func (cond *Cond) Signal() {
    45  	select {
    46  	case cond.signal <- lang.Placeholder:
    47  	default:
    48  	}
    49  }