I've been using threadpool
in Nim and have encountered the requirement that spawn
ed functions cannot accept a mutable argument. However, I want to pass a proc a Lock
, which in turn has to be mutable, according to the type of acquire
. The only way to get around this I've found is by having the lock mutable and declared in global scope, so I don't have to pass it into the function I spawn
.
But I'd really rather avoid that. I had the idea of using a pointer - so the lock could be mutable, but the pointer itself isn't - to get around this, but it looks like pointers aren't really first-class objects in Nim. I tried just declaring the parameter of waitLock
to be ref
(line 3), and I still get the complaint that acquire
must be passed a var Lock
and not a ref Lock
here. And it looks like dereferencing pointers is also done automatically, so there's no way around it...? Is there any way to get around using dynamic scoping and have the lock be explicitly passed into the proc? Is it with good reason that I can't do what I want? Or have I just missed the dereference operator in some manual? What would the cleanest way to implement this be?
import os, threadpool, locks
proc waitLock(lock: ref Lock): void =
acquire lock
echo "Child thread has lock!"
release lock
var lock: Lock
initLock lock
spawn waitLock(lock)
acquire lock
echo "Parent thread has lock!"
release lock
sync()
deinitLock lock