v2 / vlib / v / tests / concurrency / semaphore_timed_test.v
29 lines · 27 sloc · 722 bytes · 99be39cbd15d4bbb5ab14d2f870199908c00bc8d
Raw
1// vtest retry: 3
2import sync
3import time
4
5fn 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
12fn 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