Hello guys I'm trying to make a type definition that can be used to store generic data that could be used from different threads and async procedures. I looked up that in order to perform thread-safe reads/writes I have to use a Lock. I made it to this:
import locks
type
Foo[T] = ref object
value: T
lock: Lock
proc newFoo[T](value: T): Foo[T] =
var newLock: Lock
var newValue {.guard: newLock.} = value
Foo[T](value: newValue, lock: newLock)
And the procedures to make writes/reads are these:
proc getValue[T](self: Foo[T]): T =
var result: T
withLock self.lock:
result = self.value
result
proc setValue[T](self: Foo[T], value: T) =
withLock self.lock:
self.value = value
However when I run this code with actual data it gives the following warnings:
let foo = newFoo[string]("default")
echo foo.getValue
foo.setValue("If you're able to read this, it works!")
echo foo.getValue
/path/to/file.nim(25, 9) template/generic instantiation of `getValue` from here
/path/to/file.nim(14, 7) Warning: Special variable 'result' is shadowed. [ResultShadowed]
default
If you're able to read this it works!
Even though it shows the expected results these warnings are bothering me. Specially since the result variable int the getValue has to be used to return safely the value, otherwise it throws error since the procedure ends without closing the lock. Is there any suggestion or opinion? ThanksInstead of
proc getValue[T](self: Foo[T]): T =
var result: T
withLock self.lock:
result = self.value
result
use:
proc getValue[T](self: Foo[T]): T =
withLock self.lock:
result = self.value