daily pastebin goal
18%
SHARE
TWEET

[Go] Using buffered channels.

cwchen Nov 28th, 2017 141 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
Top