Skip to content

Instantly share code, notes, and snippets.

@vaibhav-kaushal
Created April 14, 2022 15:58
Show Gist options
  • Save vaibhav-kaushal/162968d24fcd27673ea0c4016955b594 to your computer and use it in GitHub Desktop.
Save vaibhav-kaushal/162968d24fcd27673ea0c4016955b594 to your computer and use it in GitHub Desktop.
A sample to show how buffered channels and tickers can be worked on together.
package main
import (
"fmt"
"sync"
"time"
)
var numberChan chan int64
func main() {
var stopAt int64 = 40
numberChan = make(chan int64, 10)
i := int64(1)
pushTicker := time.NewTicker(500 * time.Millisecond)
pullTicker := time.NewTicker(1 * time.Second)
pushDone := make(chan bool)
pullDone := make(chan bool)
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
for {
select {
case <-pushDone:
return
case <-pushTicker.C:
DoTick(i)
if i > stopAt {
pushDone <- true
wg.Done()
}
//numberChan <- i
//fmt.Println("i:", i, "at:", time.Now().Unix())
i = i + 1
}
}
}()
go func() {
for {
select {
case <-pullDone:
return
case <-pullTicker.C:
val := <-numberChan
fmt.Printf("Cap: %v \t| Len: %v \t| Value: %v \n", cap(numberChan), len(numberChan), val)
if val > stopAt {
pullDone <- true
wg.Done()
}
}
}
}()
wg.Wait()
}
func DoTick(i int64) {
if len(numberChan) > 9 {
fmt.Println("Dropping", i)
return
}
numberChan <- i
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment