Guest User

Untitled

a guest
May 25th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sync"
  6. "time"
  7. )
  8.  
  9. func main() {
  10. fmt.Println("Starting program...")
  11.  
  12. maxItemCount := 10
  13. wg := sync.WaitGroup{}
  14. processed := make(chan int)
  15. final := []int{}
  16.  
  17. for i := 0; i < maxItemCount; i++ {
  18. wg.Add(1)
  19. go doSomething(&wg, i, processed)
  20. }
  21.  
  22. go func() {
  23. for item := range processed {
  24. // Exaggerate a long processing operation when consuming channel items
  25. time.Sleep(5 * time.Second)
  26. fmt.Printf("Processed %d\n", item)
  27. final = append(final, item)
  28. }
  29. }()
  30.  
  31. wg.Wait()
  32. close(processed)
  33.  
  34. fmt.Printf("Final: %v\n", final)
  35. fmt.Println("-------------------")
  36. fmt.Printf("Initial item count: %d\n", maxItemCount)
  37. fmt.Printf("Final item count: %d\n", len(final))
  38. }
  39.  
  40. func doSomething(wg *sync.WaitGroup, input int, output chan<- int) {
  41. defer wg.Done()
  42.  
  43. fmt.Printf("[%d] Starting DoSomething\n", input)
  44.  
  45. fmt.Printf("[%d] Starting long processing\n", input)
  46. time.Sleep(2 * time.Second)
  47. fmt.Printf("[%d] Finished long processing\n", input)
  48.  
  49. output <- input * 100
  50. }
  51.  
  52. /*
  53. Starting program...
  54. [0] Starting DoSomething
  55. [0] Starting long processing
  56. [6] Starting DoSomething
  57. [6] Starting long processing
  58. [7] Starting DoSomething
  59. [7] Starting long processing
  60. [8] Starting DoSomething
  61. [8] Starting long processing
  62. [1] Starting DoSomething
  63. [1] Starting long processing
  64. [3] Starting DoSomething
  65. [3] Starting long processing
  66. [2] Starting DoSomething
  67. [2] Starting long processing
  68. [4] Starting DoSomething
  69. [4] Starting long processing
  70. [5] Starting DoSomething
  71. [5] Starting long processing
  72. [9] Starting DoSomething
  73. [9] Starting long processing
  74. [9] Finished long processing
  75. [2] Finished long processing
  76. [8] Finished long processing
  77. [7] Finished long processing
  78. [0] Finished long processing
  79. [1] Finished long processing
  80. [3] Finished long processing
  81. [4] Finished long processing
  82. [6] Finished long processing
  83. [5] Finished long processing
  84. Processed 900
  85. Processed 200
  86. Processed 700
  87. Processed 800
  88. Processed 0
  89. Processed 100
  90. Processed 300
  91. Processed 400
  92. Processed 600
  93. Final: [900 200 700 800 0 100 300 400 600]
  94. -------------------
  95. Initial item count: 10
  96. Final item count: 9
  97. */
Add Comment
Please, Sign In to add comment