1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen, sync: implement separate read/write locks for rwshared types (#5687)

This commit is contained in:
Uwe Krüger
2020-07-05 22:53:28 +02:00
committed by GitHub
parent 3cd9e2cab7
commit c3614c0e38
7 changed files with 229 additions and 19 deletions

View File

@@ -0,0 +1,58 @@
import sync
import time
struct St {
mut:
a int
}
fn f(rwshared x St, shared z St) {
for _ in 0..reads_per_thread {
rlock x { // other instances may read at the same time
time.sleep_ms(1)
assert x.a == 7 || x.a == 5
}
}
lock z {
z.a--
}
}
const (
reads_per_thread = 30
read_threads = 10
writes = 5
)
fn test_shared_lock() {
// object with separate read/write lock
rwshared x := &St{
a: 5
}
shared z := &St{
a: read_threads
}
for _ in 0..read_threads {
go f(rwshared x, shared z)
}
for i in 0..writes {
lock x { // wait for ongoing reads to finish, don't start new ones
x.a = 17 // this should never be read
time.sleep_ms(50)
x.a = if (i&1) == 0 { 7 } else { 5 }
} // now new reads are possible again
time.sleep_ms(20)
}
// wait until all read threads are finished
for finished := false; ; {
mut rr := 0
lock z {
rr = z.a
finished = z.a == 0
}
if finished {
break
}
time.sleep_ms(100)
}
}