Advertisement
Guest User

Untitled

a guest
Aug 24th, 2021
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.83 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math/rand"
  6.     "runtime"
  7.     "sync"
  8. )
  9.  
  10. const NB_WORKERS = 3000
  11. const JOB_COUNTING_TO = 10000000
  12.  
  13. var mu sync.Mutex
  14. var guard chan struct{}
  15. var nbConcurrentGoRoutines = 0
  16. var jobsDone = 0
  17.  
  18. func max(a, b int) int {
  19.     if a > b {
  20.         return a
  21.     }
  22.     return b
  23. }
  24.  
  25. func doJob(job int) {
  26.     nbConcurrentGoRoutines = max(nbConcurrentGoRoutines, runtime.NumGoroutine())
  27.  
  28.     if rand.Intn(10) == 0 {
  29.         return
  30.     }
  31.  
  32.     for i := 0; i < job; i += 1 {
  33.     }
  34.  
  35.     mu.Lock()
  36.     jobsDone += 1
  37.     mu.Unlock()
  38.  
  39.     var wg sync.WaitGroup
  40.     for i := 0; i < 18; i += 1 {
  41.         guard <- struct{}{}
  42.         wg.Add(1)
  43.         go func() {
  44.             doJob(JOB_COUNTING_TO)
  45.             wg.Done()
  46.         }()
  47.     }
  48.     wg.Wait()
  49.     <-guard
  50. }
  51.  
  52. func main() {
  53.     guard = make(chan struct{}, NB_WORKERS)
  54.     doJob(JOB_COUNTING_TO)
  55.     fmt.Println(jobsDone, nbConcurrentGoRoutines)
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement