Skip to content

Instantly share code, notes, and snippets.

@imagescape
Created October 19, 2012 04:27
Show Gist options
  • Save imagescape/3916238 to your computer and use it in GitHub Desktop.
Save imagescape/3916238 to your computer and use it in GitHub Desktop.
package main
import "fmt"
import "time"
import "runtime"
const (
MAX_UPDATES = 50
MAX_FRAMES = 25
)
const (
_ = iota
SIG_KILL
)
type Runnable interface {
Run(float64)
}
type Counter struct {
Runnable
value int
delta int
control chan int
}
func NewCounter(start, delta int) *Counter {
new_counter := Counter{
value: start,
delta: delta,
control: make(chan int),
}
return &new_counter
}
func (self *Counter) Run(rate float64) {
go func() {
ticker := time.Tick(time.Millisecond * time.Duration(rate))
for {
select {
case m := <-self.control:
switch m {
case SIG_KILL:
return
}
case <-ticker:
self.value += self.delta
default:
runtime.Gosched()
}
}
} ()
}
func main() {
fmt.Println("Counter will inc each half second")
fmt.Println("Rendering will happen each second")
fmt.Println("Will counter reach 50 before we render 25 frames?")
frame_ticker := time.Tick(time.Second)
frames := 0
counter := NewCounter(0, 1)
counter.Run(500)
for frames < MAX_FRAMES && counter.value < MAX_UPDATES {
select {
case <-frame_ticker:
fmt.Println(frames, ":", counter.value)
frames += 1
default: runtime.Gosched()
}
}
counter.control <-SIG_KILL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment