v2 / vlib / v / tests / concurrency / autolock_array2_test.v
30 lines · 27 sloc · 695 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import sync
2
3const iterations_per_thread2 = 100000
4
5fn inc_elements(shared foo []int, n int, mut sem sync.Semaphore) {
6 for _ in 0 .. iterations_per_thread2 {
7 foo[n]++
8 }
9 sem.post() // indicate that thread is finished
10}
11
12fn test_autolocked_array_2() {
13 shared abc := &[0, 0, 0]
14 mut sem := sync.new_semaphore()
15 spawn inc_elements(shared abc, 1, mut sem)
16 spawn inc_elements(shared abc, 2, mut sem)
17 for _ in 0 .. iterations_per_thread2 {
18 unsafe {
19 abc[2]++
20 }
21 }
22 // wait for the 2 coroutines to finish using the semaphore
23 for _ in 0 .. 2 {
24 sem.wait()
25 }
26 rlock abc {
27 assert unsafe { abc[1] } == iterations_per_thread2
28 assert unsafe { abc[2] } == 2 * iterations_per_thread2
29 }
30}
31