Advertisement
fcamuso

Un assaggio di Go - Video 10

Jul 8th, 2025
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.10 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "net/http"
  6.     "sync"
  7.     "time"
  8. )
  9.  
  10. func main() {
  11.     numeroRichieste := 1000
  12.     start := time.Now()
  13.  
  14.     // for i := 0; i < numeroRichieste; i++ {
  15.     //  resp, err := http.Get("https://httpbin.org/delay/1")
  16.     //  if err != nil {
  17.     //      fmt.Println("Errore:", err)
  18.     //      continue
  19.     //  }
  20.     //  resp.Body.Close()
  21.     //  fmt.Printf("Richiesta %d completata\n", i+1)
  22.     // }
  23.  
  24.     elapsed := time.Since(start)
  25.     //fmt.Printf("Tempo totale senza goroutine: %s\n", elapsed)
  26.  
  27.     start = time.Now()
  28.  
  29.     var wg sync.WaitGroup
  30.     wg.Add(numeroRichieste)
  31.  
  32.     contatore := 0
  33.     var mu sync.Mutex
  34.  
  35.     for i := 0; i < numeroRichieste; i++ {
  36.         go func(i int) {
  37.             defer wg.Done()
  38.             mu.Lock()
  39.               contatore++
  40.             mu.Unlock()
  41.  
  42.             resp, err := http.Get("https://httpbin.org/delay/1")
  43.             if err != nil {
  44.                 fmt.Printf("Errore nella richiesta %d: %v\n", i+1, err)
  45.                 return
  46.             }
  47.             resp.Body.Close()
  48.             //fmt.Printf("Richiesta %d completata\n", i+1)
  49.         }(i)
  50.     }
  51.  
  52.     wg.Wait()
  53.     elapsed = time.Since(start)
  54.     fmt.Printf("Tempo totale con goroutine: %s\n", elapsed)
  55.     fmt.Println("Contatore ", contatore)
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement