Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sync"
  6. "time"
  7. )
  8.  
  9. type msg struct {
  10. data []byte
  11. }
  12.  
  13. var wg sync.WaitGroup
  14.  
  15. func main() {
  16.  
  17. // wait group used to control the flow in the demo
  18. // Not necessarily needed in real life :)
  19. wg = sync.WaitGroup{}
  20.  
  21. c := readChan()
  22.  
  23. for i := 0; i < 100; i++ {
  24. c <- msg{
  25. data: []byte("test"),
  26. }
  27. }
  28.  
  29. close(c)
  30.  
  31. // Using the wg so the program doens't end prematurely
  32. wg.Wait()
  33.  
  34. }
  35.  
  36. // readChan creates a chan, starts a worker listening on it,
  37. // and then returns the chan so we can add things to it!
  38. func readChan() (c chan msg) {
  39.  
  40. c = make(chan msg)
  41.  
  42. go Worker(c)
  43.  
  44. return c
  45.  
  46. }
  47.  
  48. // Worker uses the chan to get messages
  49. func Worker(c chan msg) {
  50.  
  51. wg.Add(1)
  52.  
  53. fmt.Println("starting worker")
  54.  
  55. count := 0
  56. stop := false
  57.  
  58. for {
  59.  
  60. select {
  61. case v, ok := <-c:
  62.  
  63. if ok != true {
  64. stop = true
  65. }
  66.  
  67. fmt.Println(string(v.data))
  68. count++
  69. }
  70.  
  71. if stop {
  72. break
  73. }
  74.  
  75. if count > 10 {
  76. go Worker(c)
  77. break
  78. }
  79.  
  80. }
  81.  
  82. fmt.Println("blocking..")
  83. time.Sleep(time.Second * 2)
  84. fmt.Println("done")
  85. wg.Done()
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement