| 1 | import time |
| 2 | |
| 3 | struct St { |
| 4 | mut: |
| 5 | a int |
| 6 | } |
| 7 | |
| 8 | fn (shared x St) f(shared z St) { |
| 9 | for _ in 0 .. reads_per_thread { |
| 10 | rlock x { // other instances may read at the same time |
| 11 | time.sleep(time.millisecond) |
| 12 | assert x.a == 7 || x.a == 5 |
| 13 | } |
| 14 | } |
| 15 | lock z { |
| 16 | z.a-- |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | fn g() shared St { |
| 21 | shared x := St{ |
| 22 | a: 12 |
| 23 | } |
| 24 | return x |
| 25 | } |
| 26 | |
| 27 | fn h() ?shared St { |
| 28 | return error('no value') |
| 29 | } |
| 30 | |
| 31 | fn k() { |
| 32 | shared x := g() |
| 33 | shared y := h() or { |
| 34 | shared f := St{} |
| 35 | f |
| 36 | } |
| 37 | shared z := h()? |
| 38 | shared p := v |
| 39 | v := rlock z { |
| 40 | z.a |
| 41 | } |
| 42 | lock y, z; rlock x, p { |
| 43 | z.a = x.a + y.a |
| 44 | } |
| 45 | println(v) |
| 46 | } |
| 47 | |
| 48 | const reads_per_thread = 30 |
| 49 | const read_threads = 10 |
| 50 | const writes = 5 |
| 51 | |
| 52 | fn test_shared_lock() { |
| 53 | // object with separate read/write lock |
| 54 | shared x := &St{ |
| 55 | a: 5 |
| 56 | } |
| 57 | shared z := &St{ |
| 58 | a: read_threads |
| 59 | } |
| 60 | for _ in 0 .. read_threads { |
| 61 | spawn x.f(shared z) |
| 62 | } |
| 63 | for i in 0 .. writes { |
| 64 | lock x { // wait for ongoing reads to finish, don't start new ones |
| 65 | x.a = 17 // this value should never be read |
| 66 | time.sleep(50 * time.millisecond) |
| 67 | x.a = if (i & 1) == 0 { 7 } else { 5 } |
| 68 | } // now new reads are possible again |
| 69 | time.sleep(20 * time.millisecond) |
| 70 | } |
| 71 | // wait until all read threads are finished |
| 72 | for finished := false; true; { |
| 73 | mut rr := 0 |
| 74 | rlock z { |
| 75 | rr = z.a |
| 76 | finished = z.a == 0 |
| 77 | } |
| 78 | if finished { |
| 79 | break |
| 80 | } |
| 81 | time.sleep(100 * time.millisecond) |
| 82 | } |
| 83 | } |
| 84 | |