Created
May 3, 2021 10:36
-
-
Save Neurostep/689729b069e1d37f8f8fb8feed5c81ed to your computer and use it in GitHub Desktop.
Go: Simple non-blocking FIFO channel
This file contains hidden or 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
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