1
0
Fork 0
burlesque/counter.go

69 lines
1.1 KiB
Go
Raw Normal View History

2014-07-10 12:19:39 +00:00
package main
2014-07-12 10:38:35 +00:00
import (
"sync"
)
2014-07-10 12:19:39 +00:00
const (
MaxIndex = ^uint(0)
)
type (
2014-07-15 19:41:38 +00:00
// Counter is responsible for operating queue read and write indexes
2014-07-10 12:19:39 +00:00
Counter struct {
2014-07-15 19:41:38 +00:00
WriteIndex uint // Number of the record last written to the queue
ReadIndex uint // Number of the record last read from the queue
// If WriteIndex is greater than ReadIndex then there are unread messages
// If WriteIndex is less tham ReadIndex then MaxIndex was reached
2014-07-16 18:27:30 +00:00
Read chan uint
2014-07-15 19:41:38 +00:00
mutex sync.Mutex
2014-07-16 17:45:26 +00:00
streaming *sync.Cond
2014-07-10 12:19:39 +00:00
}
)
2014-07-16 17:45:26 +00:00
func NewCounter(wi, ri uint) *Counter {
m := &sync.Mutex{}
m.Lock()
c := &Counter{
2014-07-12 10:38:35 +00:00
WriteIndex: wi,
ReadIndex: ri,
stream: make(chan uint),
2014-07-16 17:45:26 +00:00
streaming: sync.NewCond(m),
2014-07-12 10:38:35 +00:00
}
2014-07-16 17:45:26 +00:00
go c.Stream()
2014-07-10 12:19:39 +00:00
return c
}
2014-07-12 10:38:35 +00:00
func (c *Counter) Write(proc func(i uint) bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
ok := proc(c.WriteIndex + 1)
if ok {
c.WriteIndex++
2014-07-16 17:45:26 +00:00
c.streaming.Signal()
2014-07-10 12:19:39 +00:00
}
}
func (c *Counter) Distance() uint {
2014-07-12 10:38:35 +00:00
d := c.WriteIndex - c.ReadIndex
2014-07-10 12:19:39 +00:00
if d < 0 {
d += MaxIndex
}
return d
}
2014-07-12 10:38:35 +00:00
func (c *Counter) Stream() {
2014-07-16 17:45:26 +00:00
for {
if c.Distance() == 0 {
c.streaming.Wait()
}
2014-07-12 10:38:35 +00:00
c.stream <- c.ReadIndex + 1
c.ReadIndex++
2014-07-10 12:19:39 +00:00
}
}