Created
November 8, 2022 16:31
-
-
Save juanpabloaj/98297c951fa117c0710ef41726d15c13 to your computer and use it in GitHub Desktop.
Channel example, channel as queue with discard of messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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