提交 ae79ac04 作者: Brian Tiger Chow

feat(util/delay) add Delay

License: MIT
Signed-off-by: 's avatarBrian Tiger Chow <brian@perfmode.com>
上级 866ef728
package delay
import (
"sync"
"time"
)
// Delay makes it easy to add (threadsafe) configurable delays to other
// objects.
type D interface {
Set(time.Duration) time.Duration
Wait()
}
// Fixed returns a delay with fixed latency
func Fixed(t time.Duration) D {
return &delay{t: t}
}
type delay struct {
l sync.RWMutex
t time.Duration
}
// TODO func Variable(time.Duration) D returns a delay with probablistic latency
func (d *delay) Set(t time.Duration) time.Duration {
d.l.Lock()
defer d.l.Unlock()
prev := d.t
d.t = t
return prev
}
func (d *delay) Wait() {
d.l.RLock()
defer d.l.RUnlock()
time.Sleep(d.t)
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论