| 1 | import sync |
| 2 | import time |
| 3 | |
| 4 | struct St { |
| 5 | mut: |
| 6 | a int |
| 7 | } |
| 8 | |
| 9 | fn (shared x St) f(shared z St) { |
| 10 | for _ in 0 .. reads_per_thread { |
| 11 | rlock x { // other instances may read at the same time |
| 12 | time.sleep(time.millisecond) |
| 13 | assert x.a == 7 || x.a == 5 |
| 14 | } |
| 15 | } |
| 16 | lock z { |
| 17 | z.a-- |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | fn g() shared St { |
| 22 | shared x := St{a: 12 } |
| 23 | return x |
| 24 | } |
| 25 | |
| 26 | fn h() ?shared St { |
| 27 | return error('no value') |
| 28 | } |
| 29 | |
| 30 | fn k() { |
| 31 | shared x := g() |
| 32 | shared y := h() or { |
| 33 | shared f := St{} |
| 34 | f |
| 35 | } |
| 36 | shared z := h()? |
| 37 | shared p := v |
| 38 | v := rlock z { z.a } |
| 39 | rlock x; lock y, z; rlock p { |
| 40 | z.a = x.a + y.a |
| 41 | } |
| 42 | println(v) |
| 43 | } |
| 44 | |
| 45 | const ( |
| 46 | reads_per_thread = 30 |
| 47 | read_threads = 10 |
| 48 | writes = 5 |
| 49 | ) |
| 50 | |
| 51 | fn test_shared_lock() { |
| 52 | // object with separate read/write lock |
| 53 | shared x := &St { |
| 54 | a: 5 |
| 55 | } |
| 56 | shared z := |
| 57 | &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;; { |
| 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 | |