Advertisement
XAgent-Smith

golang-libs

Feb 2nd, 2021
1,392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.75 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "sync"
  6.     "time"
  7.  
  8.     sem "github.com/oscuro1111/golang-libs/semaphore"
  9. )
  10.  
  11. var (
  12.     log = fmt.Println
  13. )
  14.  
  15. type Res struct {
  16.     data int
  17. }
  18.  
  19. func work(pool *sem.Semaphore, wg *sync.WaitGroup) {
  20.  
  21.     resource := pool.GetResource().(Res)
  22.  
  23.     for i := 10; i > 0; i-- {
  24.  
  25.         resource.data++
  26.         time.Sleep(10 * time.Millisecond)
  27.     }
  28.  
  29.     pool.ReleaseResource(resource)
  30.     wg.Done()
  31.     return
  32. }
  33.  
  34. func main() {
  35.     resources := []interface {
  36.     }{
  37.         Res{data: 0}, Res{data: 0}, Res{data: 0},
  38.     }
  39.  
  40.     wg := &sync.WaitGroup{}
  41.     pool := sem.NewSemaphore(resources)
  42.  
  43.     numThreads := 100
  44.  
  45.     for i := numThreads; i > 0; i-- {
  46.         wg.Add(1)
  47.         go work(pool, wg)
  48.     }
  49.  
  50.     wg.Wait()
  51.  
  52.     for _, val := range resources {
  53.         log(val.(Res))
  54.     }
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement