Skip to content

Instantly share code, notes, and snippets.

@localhots
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save localhots/2d995c87f31ff80a939a to your computer and use it in GitHub Desktop.

Select an option

Save localhots/2d995c87f31ff80a939a to your computer and use it in GitHub Desktop.
type Counter struct {
Write uint
Read uint
stream chan uint
inLoop bool
}
func NewCounter(wi, ri uint) *Counter {
c := &Counter{Write: wi, Read: ri}
c.stream = make(chan uint)
go c.Loop()
return c
}
func (c *Counter) Incr() {
c.Write++
if !c.inLoop {
c.inLoop = true
go c.Loop()
}
}
func (c *Counter) Next() uint {
return <-c.stream
}
func (c *Counter) Distance() uint {
return c.Write - c.Read
}
func (c *Counter) Loop() {
for c.Write > c.Read {
c.stream <- c.Read + 1
c.Read++
}
c.inLoop = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment