counter.go 632 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package metrics
  2. type Counter interface {
  3. Clear()
  4. Count() int64
  5. Dec(int64)
  6. Inc(int64)
  7. }
  8. type counter struct {
  9. in, out chan int64
  10. reset chan bool
  11. }
  12. func NewCounter() Counter {
  13. c := &counter{make(chan int64), make(chan int64), make(chan bool)}
  14. go c.arbiter()
  15. return c
  16. }
  17. func (c *counter) Clear() {
  18. c.reset <- true
  19. }
  20. func (c *counter) Count() int64 {
  21. return <-c.out
  22. }
  23. func (c *counter) Dec(i int64) {
  24. c.in <- -i
  25. }
  26. func (c *counter) Inc(i int64) {
  27. c.in <- i
  28. }
  29. func (c *counter) arbiter() {
  30. var count int64
  31. for {
  32. select {
  33. case i := <-c.in: count += i
  34. case c.out <- count:
  35. case <-c.reset: count = 0
  36. }
  37. }
  38. }