goroutine_select2.go 849 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "runtime"
  6. )
  7. func main() {
  8. // setting GOMAXPROCS to 2 gives +- 22% performance increase,
  9. // but increasing the number doesn't increase the performance
  10. // without GOMAXPROCS: +- 86000
  11. // setting GOMAXPROCS to 2: +- 105000
  12. // setting GOMAXPROCS to 3: +- 94000
  13. runtime.GOMAXPROCS(2)
  14. ch1 := make(chan int)
  15. ch2 := make(chan int)
  16. go pump1(ch1)
  17. go pump2(ch2)
  18. go suck(ch1, ch2)
  19. time.Sleep(1e9)
  20. }
  21. func pump1(ch chan int) {
  22. for i:=0; ; i++ {
  23. ch <- i*2
  24. }
  25. }
  26. func pump2(ch chan int) {
  27. for i:=0; ; i++ {
  28. ch <- i+5
  29. }
  30. }
  31. func suck(ch1,ch2 chan int) {
  32. for i := 0; ; i++ {
  33. select {
  34. case v := <- ch1:
  35. fmt.Printf("%d - Received on channel 1: %d\n", i, v)
  36. case v := <- ch2:
  37. fmt.Printf("%d - Received on channel 2: %d\n", i, v)
  38. }
  39. }
  40. }