Advertisement
cwchen

[Go] Using buffered channels.

Nov 28th, 2017
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.46 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5.     "os"
  6.     "sync"
  7. )
  8.  
  9. func main() {
  10.     // A goroutine-safe console printer.
  11.     logger := log.New(os.Stdout, "", 0)
  12.  
  13.     // Sync among all goroutines.
  14.     var wg sync.WaitGroup
  15.  
  16.     // Make a buffered channel.
  17.     ch := make(chan int, 10)
  18.  
  19.     for i := 1; i <= 10; i++ {
  20.         ch <- i
  21.         wg.Add(1)
  22.         go func() {
  23.             defer wg.Done()
  24.             logger.Println("Print from goroutine ", <-ch)
  25.         }()
  26.     }
  27.  
  28.     logger.Println("Print from main")
  29.     wg.Wait()
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement