Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Created November 8, 2022 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpabloaj/98297c951fa117c0710ef41726d15c13 to your computer and use it in GitHub Desktop.
Save juanpabloaj/98297c951fa117c0710ef41726d15c13 to your computer and use it in GitHub Desktop.
Channel example, channel as queue with discard of messages
// go playground
// https://go.dev/play/p/3HjtqJlbMnE
package main
import (
"log"
"time"
)
func main() {
log.SetFlags(log.Lmicroseconds)
queueSize := 3
ch := make(chan int, queueSize)
go func() {
for m := range ch {
log.Printf("ok msg %d received", m)
time.Sleep(10 * time.Millisecond)
}
}()
for i := 0; i < 10; i++ {
log.Printf("message %d, queue slots used %d/%d", i, len(ch), queueSize)
select {
case ch <- i:
case <-time.After(5 * time.Millisecond):
log.Printf("timeout! message %d discarded", i)
}
}
time.Sleep(1 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment