| 1 | import sync |
| 2 | import rand |
| 3 | import time |
| 4 | |
| 5 | fn test_spinlock() { |
| 6 | mut counter := 0 |
| 7 | mut s := sync.new_spin_lock() |
| 8 | defer { |
| 9 | s.destroy() |
| 10 | } |
| 11 | num_threads := 10 |
| 12 | iterations := 10 |
| 13 | mut wg := sync.new_waitgroup() |
| 14 | wg.add(num_threads) |
| 15 | |
| 16 | for _ in 0 .. num_threads { |
| 17 | spawn fn (mut wg sync.WaitGroup, s &sync.SpinLock, counter_ref &int, iterations int) { |
| 18 | for _ in 0 .. iterations { |
| 19 | s.lock() |
| 20 | |
| 21 | unsafe { |
| 22 | tmp := *counter_ref |
| 23 | randval := rand.intn(100) or { 1 } |
| 24 | time.sleep(randval * time.nanosecond) |
| 25 | |
| 26 | (*counter_ref) = tmp + 1 |
| 27 | } |
| 28 | s.unlock() |
| 29 | } |
| 30 | wg.done() |
| 31 | }(mut wg, s, &counter, iterations) |
| 32 | } |
| 33 | wg.wait() |
| 34 | assert counter == num_threads * iterations |
| 35 | |
| 36 | // test try_lock() |
| 37 | s.lock() |
| 38 | assert s.try_lock() == false |
| 39 | s.unlock() |
| 40 | assert s.try_lock() == true |
| 41 | assert s.try_lock() == false |
| 42 | } |
| 43 | |