I have a slightly different version with the writer threads doing
`table[threadId] = currentIter` and readers just echoing the table. Most of the
trouble was to make the compiler stop complaining, so be sure to compile with
`--threadAnalysis:off` and annotate the procs with `.thread` pragma.
import std / [os, tables], thrsync
const
numThreads = 5
var
m: RwMonitor # global object of monitor class
readers: array[numThreads, Thread[int]]
writers: array[numThreads, Thread[int]]
table: Table[string, string]
proc read(id: int) {.thread.} =
# each reader attempts to read 10 times
for i in 0 ..< 10:
readWith m:
echo "#", id, " reads table: ", table
sleep(500)
proc write(id: int) {.thread.} =
# each writer attempts to write 5 times
for i in 0 ..< 5:
writeWith m:
echo "#", id, " writes to table..."
table[$id] = $i
sleep(250)
sleep(250)
proc main =
initRwMonitor(m)
table = initTable[string, string]()
for i in 0 ..< numThreads:
# creating threads which execute writer function
createThread(writers[i], write, i)
# creating threads which execute reader function
createThread(readers[i], read, i)
joinThreads(readers)
joinThreads(writers)
doAssert table == {"4": "4", "1": "4", "2": "4", "3": "4", "0":
"4"}.toTable
destroyRwMonitor(m)
main()
Run