emin_int11

understanding locking in Go

Mar 18th, 2025
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sync"
  6. "sync/atomic"
  7. )
  8.  
  9. var (
  10. atomicLock int32 = 0
  11. )
  12.  
  13. func lock() {
  14. for {
  15. if atomic.CompareAndSwapInt32(&atomicLock, 0, 1) {
  16. return
  17. }
  18. }
  19. }
  20.  
  21. func unlock() {
  22. atomic.StoreInt32(&atomicLock, 0)
  23. }
  24.  
  25. func main() {
  26. var wg sync.WaitGroup
  27.  
  28. for i := range 10 {
  29. wg.Add(1)
  30.  
  31. go func(i int) {
  32. defer wg.Done()
  33.  
  34. fmt.Printf("%d thread tries to lock\n", i)
  35. lock()
  36. fmt.Printf("%d thread succesfully lock\n", i)
  37. unlock()
  38. fmt.Printf("%d thread succesfully unlock\n", i)
  39. }(i)
  40. }
  41.  
  42. wg.Wait()
  43. }
  44.  
  45.  
  46. Output:
  47. 5 thread succesfully lock <= lock
  48. 5 thread succesfully unlock <= unlock
  49. 0 thread succesfully lock <= lock
  50. 1 thread tries to lock <= waits to unlock from 0
  51. 0 thread succesfully unlock <= unlock successfully
  52. 8 thread succesfully lock <= lock
  53. 8 thread succesfully unlock <= unlock
  54. 4 thread tries to lock <= wait to lock
  55. 1 thread succesfully lock <= lock
  56. 1 thread succesfully unlock
  57. 2 thread succesfully lock
  58. 2 thread succesfully unlock
  59. 3 thread succesfully lock
  60. 3 thread succesfully unlock
  61. 4 thread succesfully lock
  62. 4 thread succesfully unlock
  63. 7 thread succesfully lock
  64. 9 thread succesfully lock
  65. 7 thread succesfully unlock
  66. 9 thread succesfully unlock
  67. 6 thread succesfully lock
  68. 6 thread succesfully unlock
  69.  
Advertisement
Add Comment
Please, Sign In to add comment