Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "time"
  6. )
  7.  
  8. func gen() <-chan int {
  9. ch := make(chan int, 100)
  10.  
  11. go func() {
  12. defer close(ch)
  13. for i := 0; i < 20; i++ {
  14. fmt.Printf("gen %d\n", i)
  15. ch <- i
  16. time.Sleep(100 * time.Millisecond)
  17. }
  18. }()
  19.  
  20. return ch
  21. }
  22.  
  23. func mut(in <-chan int) <-chan int {
  24. ch := make(chan int, 200)
  25.  
  26. go func() {
  27. defer close(ch)
  28. for v := range in {
  29. ch <- v * 10
  30. }
  31. }()
  32.  
  33. return ch
  34. }
  35.  
  36. func sub(ch <-chan int) {
  37. const BufLimit = 5
  38. buf := make([]int, 0, BufLimit)
  39.  
  40. for v := range ch {
  41. fmt.Printf("sub %d\n", v)
  42. buf = append(buf, v)
  43. if len(buf) == BufLimit {
  44. flush(buf)
  45. buf = buf[:0]
  46.  
  47. }
  48. time.Sleep(300 * time.Millisecond)
  49. }
  50. }
  51.  
  52. func flush(buf []int) {
  53. fmt.Print("flush ")
  54. for _, v := range buf {
  55. fmt.Printf("%d ", v)
  56. }
  57. fmt.Println()
  58. }
  59.  
  60. func main() {
  61. ch1 := gen()
  62. ch2 := mut(ch1)
  63. sub(ch2)
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement