Last active
August 29, 2015 14:02
-
-
Save localhots/2d995c87f31ff80a939a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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