v2 / vlib / v / tests / concurrency / break_in_lock_test.v
54 lines · 48 sloc · 889 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import time
2
3struct AA {
4mut:
5 b string
6}
7
8const run_time = time.millisecond * 500 // must be big enough to ensure threads have started
9
10const sleep_time = time.millisecond * 2000
11
12fn test_return_lock() {
13 start := time.now()
14 shared s := AA{'3'}
15 spawn printer(shared s, start)
16 spawn fn (shared s AA, start time.Time) {
17 for {
18 reader(shared s)
19 if time.now() - start > run_time {
20 eprintln('> ${@FN} exited')
21 exit(0)
22 }
23 }
24 }(shared s, start)
25 time.sleep(sleep_time)
26 assert false
27}
28
29fn printer(shared s AA, start time.Time) {
30 for {
31 lock s {
32 assert s.b in ['0', '1', '2', '3', '4', '5']
33 }
34 if time.now() - start > run_time {
35 eprintln('> ${@FN} exited')
36 exit(0)
37 }
38 }
39}
40
41fn reader(shared s AA) {
42 mut i := 0
43 for {
44 i++
45 x := i.str()
46 lock s {
47 s.b = x
48 if s.b == '5' {
49 // this test checks if cgen unlocks the mutex here
50 break
51 }
52 }
53 }
54}
55