Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "sync"
- "sync/atomic"
- )
- var (
- atomicLock int32 = 0
- )
- func lock() {
- for {
- if atomic.CompareAndSwapInt32(&atomicLock, 0, 1) {
- return
- }
- }
- }
- func unlock() {
- atomic.StoreInt32(&atomicLock, 0)
- }
- func main() {
- var wg sync.WaitGroup
- for i := range 10 {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- fmt.Printf("%d thread tries to lock\n", i)
- lock()
- fmt.Printf("%d thread succesfully lock\n", i)
- unlock()
- fmt.Printf("%d thread succesfully unlock\n", i)
- }(i)
- }
- wg.Wait()
- }
- Output:
- 5 thread succesfully lock <= lock
- 5 thread succesfully unlock <= unlock
- 0 thread succesfully lock <= lock
- 1 thread tries to lock <= waits to unlock from 0
- 0 thread succesfully unlock <= unlock successfully
- 8 thread succesfully lock <= lock
- 8 thread succesfully unlock <= unlock
- 4 thread tries to lock <= wait to lock
- 1 thread succesfully lock <= lock
- 1 thread succesfully unlock
- 2 thread succesfully lock
- 2 thread succesfully unlock
- 3 thread succesfully lock
- 3 thread succesfully unlock
- 4 thread succesfully lock
- 4 thread succesfully unlock
- 7 thread succesfully lock
- 9 thread succesfully lock
- 7 thread succesfully unlock
- 9 thread succesfully unlock
- 6 thread succesfully lock
- 6 thread succesfully unlock
Advertisement
Add Comment
Please, Sign In to add comment