Advertisement
cwchen

[Go] Using goroutine.

Nov 28th, 2017
864
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.62 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 between goroutines.
  14.     var wg sync.WaitGroup
  15.  
  16.     // Add goroutine 1.
  17.     wg.Add(1)
  18.     go func() {
  19.         defer wg.Done()
  20.         logger.Println("Print from goroutine 1")
  21.     }()
  22.  
  23.     // Add goroutine 2.
  24.     wg.Add(1)
  25.     go func() {
  26.         defer wg.Done()
  27.         logger.Println("Print from goroutine 2")
  28.     }()
  29.  
  30.     // Add goroutine 3.
  31.     wg.Add(1)
  32.     go func() {
  33.         defer wg.Done()
  34.         logger.Println("Print from goroutine 3")
  35.     }()
  36.  
  37.     logger.Println("Print from main")
  38.  
  39.     // Wait all goroutines.
  40.     wg.Wait()
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement