| 1 | // vtest retry: 3 |
| 2 | import sync |
| 3 | import time |
| 4 | |
| 5 | fn run_forever(shared foo []int, mut sem sync.Semaphore) { |
| 6 | for { |
| 7 | foo[0]++ |
| 8 | } |
| 9 | sem.post() // indicate that thread is finished - never happens |
| 10 | } |
| 11 | |
| 12 | fn test_semaphore() { |
| 13 | shared abc := &[0] |
| 14 | mut sem := sync.new_semaphore() |
| 15 | spawn run_forever(shared abc, mut sem) |
| 16 | for _ in 0 .. 1000 { |
| 17 | unsafe { abc[0]-- } |
| 18 | } |
| 19 | // wait for the 2 coroutines to finish using the semaphore |
| 20 | stopwatch := time.new_stopwatch() |
| 21 | mut elapsed := stopwatch.elapsed() |
| 22 | if !sem.timed_wait(200 * time.millisecond) { |
| 23 | // we should come here due to timeout |
| 24 | elapsed = stopwatch.elapsed() |
| 25 | } |
| 26 | elapsed_ms := f64(elapsed) / time.millisecond |
| 27 | println('elapsed: ${elapsed_ms:.1f}ms') |
| 28 | assert elapsed_ms >= 190.0 |
| 29 | } |
| 30 | |