Guest User

Untitled

a guest
Sep 9th, 2023
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.82 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "log"
  6.     "sync"
  7.     "time"
  8. )
  9.  
  10. func print(text string, i int) {
  11.     time.Sleep(1 * time.Second)
  12.     log.Println(text, i)
  13. }
  14.  
  15. func main() {
  16.     var wg sync.WaitGroup
  17.     textGoroutine := "use go routing : "
  18.     textNoGoroutine := "no use go routing : "
  19.     now := time.Now()
  20.  
  21.     // looping function that use go routine
  22.     for i := 0; i < 5; i++ {
  23.         wg.Add(1)
  24.         go func(i int) {
  25.             print(textGoroutine, i)
  26.             wg.Done()
  27.         }(i)
  28.     }
  29.  
  30.     wg.Wait()
  31.     // print time usage with go routine
  32.     log.Println(textGoroutine, time.Since(now))
  33.     fmt.Println()
  34.  
  35.     // initiate time now , to reset time start
  36.     now = time.Now()
  37.  
  38.     // looping function that no use go routine
  39.     for i := 0; i < 5; i++ {
  40.         print(textNoGoroutine, i)
  41.     }
  42.  
  43.     // print time usage with no go routine
  44.     log.Println(textNoGoroutine, time.Since(now))
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment