I'm developing a library that maintains a global pool of resources that can be seen in both thread and non-threaded contexts. Rather than jump into great detail, let show this with a silly example:
import strutils
import jester
var someGlobal: string = "value at the moment"
var someThread {.threadvar.}: string
proc getSomeMain(): string =
result = "copy of $1".format(someGlobal)
proc getSomeFromThread(): string {.gcsafe.} =
someThread = "copy of $1".format(someGlobal)
return someThread
someGlobal = "another change"
var x = getSomeMain()
echo x
routes:
get "/":
var y = getSomeFromThread()
resp y
Everything works great.
But, I ask, would it be possible to write a generic equivalent of "getSome". Something like:
proc getSome(): string =
if MAGIC_DETECT_METHOD:
return "copy of $1".format(someGlobal)
else:
someThread = "copy of $1".format(someGlobal)
return someThread
Or, if not at runtime, some kind of compile-time thing that detects whether "getSome" is being called from a thread, such as a Macro or Template.
I apologize if the answer to this is well documented somewhere. I've not been able to find an answer yet.
I'm not sure, but maybe this helps a little:
let mainThread = getThreadId()
proc isMainThread(): bool = getThreadId() == mainThread