I wanted to add more examples to <https://nim-lang.org/docs/typedthreads.html>
as I feel that some modules lack documentation.
I wrote a small program to show how to share memory between threads in Nim:
import locks
type Example = ref object
s: string
c: int
lock: Lock
proc newExample(): Example =
new(result, proc(eo: Example) =
deinitLock(eo.lock)
)
initLock(result.lock)
proc threadFunc(obj: Example) {.thread.} =
withLock obj.lock:
obj.s.add($obj.c)
inc obj.c
proc threadHandler() =
var thr: array[0..4, Thread[Example]]
var myObj = newExample()
for i in 0..high(thr):
createThread(thr[i], threadFunc, myObj)
joinThreads(thr)
echo myObj[]
echo "Work"
threadHandler()
echo "Done."
Run
The issue is that this program crashes, but only on windows, and only about 10%
of the time. I suspect this is a race condition, but I cannot find it. I have
no stack trace from the crash, so I cannot easily understand what is going on.
The crash occurs as often on `-d:debug`, `-d:release` and `-d:danger`. I'm
using Nim 2.0.2 (so with ORC)
Apart from the crash, I'm getting a warning that `Warning: A custom '=destroy'
hook which takes a 'var T' parameter is deprecated`. This is because the
destructor of my Example object needs to deinitLock the lock, so I need a `var
Example` to do so. Is there a way to get around this warning ?