Advertisement
Falexom

Untitled

Apr 16th, 2024
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.38 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math/rand"
  6.     "sync"
  7.     "time"
  8. )
  9.  
  10. type Semaphore interface {
  11.     Acquire(int)
  12.     Release()
  13. }
  14.  
  15. type countingSemaphore struct {
  16.     counter  int64
  17.     maxCount int64
  18.     open     bool
  19. }
  20.  
  21. func NewSemaphore(MaxCount int) *countingSemaphore {
  22.     return &countingSemaphore{
  23.         counter:  0,
  24.         maxCount: int64(MaxCount),
  25.         open:     true,
  26.     }
  27. }
  28.  
  29. func (c *countingSemaphore) Acquire(val int) {
  30.     fmt.Printf("Current state: %d\n", c.counter)
  31.     if c.counter >= c.maxCount {
  32.         c.open = false
  33.  
  34.         for !c.open {
  35.             var mutex sync.Mutex
  36.             cond := sync.NewCond(&mutex)
  37.             cond.L.Lock()
  38.             cond.Wait()
  39.         }
  40.         fmt.Printf("%d approved\n", val)
  41.         c.counter++
  42.         return
  43.     } else {
  44.         fmt.Printf("%d approved\n", val)
  45.         c.counter++
  46.         return
  47.     }
  48. }
  49.  
  50. func (c *countingSemaphore) Release(val int) {
  51.     fmt.Printf("%d leaved\n", val)
  52.     if c.counter >= c.maxCount {
  53.         c.open = true
  54.         c.counter--
  55.         return
  56.     } else {
  57.         c.counter--
  58.         return
  59.     }
  60. }
  61.  
  62. func runTime(value int, cs *countingSemaphore) {
  63.     fmt.Printf("%d entered loop\n", value)
  64.  
  65.     for {
  66.         min := int64(1000000000)
  67.         max := int64(10000000000)
  68.         randomNumber := rand.Int63n(max-min+1) + min
  69.         cs.Acquire(value)
  70.         time.Sleep(time.Duration(randomNumber))
  71.         cs.Release(value)
  72.     }
  73. }
  74.  
  75. func main() {
  76.     fmt.Println("Start")
  77.     sem := NewSemaphore(3)
  78.  
  79.     for i := 5; i < 10; i++ {
  80.         go runTime(i, sem)
  81.     }
  82.     select {}
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement