Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. // You can edit this code!
  2. // Click here and start typing.
  3. package main
  4.  
  5. import (
  6. "container/list"
  7. "fmt"
  8. "time"
  9. )
  10.  
  11. type Scatter struct {
  12. join chan chan interface{}
  13. send chan interface{}
  14. joined *list.List
  15. }
  16.  
  17. func NewScatter() *Scatter {
  18. scatter := &Scatter{}
  19. scatter.join = make(chan chan interface{})
  20. scatter.send = make(chan interface{})
  21. scatter.joined = list.New()
  22.  
  23. go scatter.run()
  24.  
  25. return scatter
  26. }
  27.  
  28. func (s *Scatter) run() {
  29. for {
  30. select {
  31. case newR := <-s.join:
  32. s.joined.PushBack(newR)
  33. case newV := <-s.send:
  34. for el := s.joined.Front(); el != nil; el = el.Next() {
  35. client, ok := el.Value.(chan interface{})
  36. if ok {
  37. client <- newV
  38. }
  39. }
  40. }
  41. }
  42. }
  43.  
  44. func (s *Scatter) Join(receiver chan interface{}) {
  45. s.join <- receiver
  46. }
  47.  
  48. func (s *Scatter) Send(value interface{}) {
  49. s.send <- value
  50. }
  51.  
  52. func main() {
  53. scatter := NewScatter()
  54.  
  55. ch1 := make(chan interface{})
  56. ch2 := make(chan interface{})
  57. ch3 := make(chan interface{})
  58.  
  59. scatter.Join(ch1)
  60. scatter.Join(ch2)
  61. scatter.Join(ch3)
  62.  
  63. go func() {
  64. for {
  65. select {
  66. case val := <-ch1:
  67. fmt.Println("ch1: ", val)
  68. case val := <-ch2:
  69. fmt.Println("ch2: ", val)
  70. case val := <-ch3:
  71. fmt.Println("ch3: ", val)
  72. }
  73. }
  74. }()
  75.  
  76. scatter.Send(10)
  77. scatter.Send(20)
  78. scatter.Send(30)
  79.  
  80. time.Sleep(100 * time.Millisecond)
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement