Skip to content

Instantly share code, notes, and snippets.

@Neurostep
Created May 3, 2021 10:36
Show Gist options
  • Save Neurostep/689729b069e1d37f8f8fb8feed5c81ed to your computer and use it in GitHub Desktop.
Save Neurostep/689729b069e1d37f8f8fb8feed5c81ed to your computer and use it in GitHub Desktop.
Go: Simple non-blocking FIFO channel
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
ch := make(chan int, 10)
for j := 0; j < 5; j++ {
wg.Add(1)
go func(j int) {
for i := 10*j + 1; i < 10 * j + 10; i++ {
push(ch, i)
}
wg.Done()
}(j)
}
wg.Wait()
close(ch)
for v := range ch {
fmt.Printf("THE VALUE LEFT: %d\n", v)
}
fmt.Println("finished")
}
func push(bufCh chan int, val int) {
select {
case bufCh <- val:
default:
t := <- bufCh
fmt.Printf("discarding value %d...\n", t)
fmt.Printf("push %d value again...\n", val)
push(bufCh, val)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment