Advertisement
Falexom

Untitled

Apr 12th, 2024
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.81 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "errors"
  5.     "fmt"
  6.     "math/rand"
  7.     "sync/atomic"
  8.     "time"
  9. )
  10.  
  11. type Mutexx interface {
  12.     Lock()
  13.     Unlock()
  14.     TestLock()
  15. }
  16.  
  17. type Mutex struct {
  18.     locked int32
  19. }
  20.  
  21. func (m *Mutex) Lock() {
  22.     currentMutexState := atomic.LoadInt32(&m.locked)
  23.  
  24.     if currentMutexState == 0 {
  25.         atomic.StoreInt32(&m.locked, 1)
  26.     } else {
  27.         err := errors.New("can't lock locked mutex")
  28.         fmt.Println(err)
  29.         return
  30.     }
  31. }
  32.  
  33. func (m *Mutex) Unlock() {
  34.     currentMutexState := atomic.LoadInt32(&m.locked)
  35.  
  36.     if currentMutexState == 1 {
  37.         atomic.StoreInt32(&m.locked, 0)
  38.     } else {
  39.         err := errors.New("can't unlock unlocked mutex")
  40.         fmt.Println(err)
  41.         return
  42.     }
  43. }
  44.  
  45. func (m *Mutex) lockedOrNot() bool {
  46.     if m.locked == 0 {
  47.         return false
  48.     } else {
  49.         return true
  50.     }
  51. }
  52.  
  53. type testData struct {
  54.     value int
  55.     mu    *Mutex
  56. }
  57.  
  58. func (t *testData) setData(newValue int) bool {
  59.     if t.mu.lockedOrNot() {
  60.         err := errors.New("can't store while mutex locked")
  61.         fmt.Println(err)
  62.         return false
  63.     } else {
  64.         t.mu.Lock()
  65.         t.value = newValue
  66.         fmt.Printf("%d successfully changed", t.value)
  67.         t.mu.Unlock()
  68.         return true
  69.     }
  70. }
  71.  
  72. func testCase(value int, mu *Mutex) {
  73.     fmt.Printf("%d entered loop\n", value)
  74.  
  75.     for {
  76.         td := &testData{mu: mu}
  77.         fmt.Printf("%d current state of mutex\n", atomic.LoadInt32(&mu.locked))
  78.         min := int64(1000000000)
  79.         max := int64(10000000000)
  80.         randomNumber := rand.Int63n(max-min+1) + min
  81.  
  82.         if td.setData(value) {
  83.             fmt.Printf("%d was stored\n", value)
  84.             time.Sleep(time.Duration(randomNumber))
  85.             fmt.Printf("%d unlocked mutex\n", value)
  86.         } else {
  87.             time.Sleep(time.Duration(randomNumber))
  88.             fmt.Printf("%d blocked mutex\n", td.value)
  89.         }
  90.     }
  91. }
  92.  
  93. func main() {
  94.     fmt.Println("start")
  95.     mu := &Mutex{}
  96.     for i := 5; i < 10; i++ {
  97.         go testCase(i, mu)
  98.     }
  99.     select {}
  100. }
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement