Skip to content

Instantly share code, notes, and snippets.

@michaelsbradleyjr
Last active February 25, 2021 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelsbradleyjr/c1118612952ca6efb273f4bb2d449f6d to your computer and use it in GitHub Desktop.
Save michaelsbradleyjr/c1118612952ca6efb273f4bb2d449f6d to your computer and use it in GitHub Desktop.
import os, stew/faux_closures, threadpool
type
Sob = ref object
key: int
type
Rob = ref object
sub: Sob
let myobject = Rob(sub: Sob(key: 42))
var somenum = myobject.sub.key
proc sendSignal(data: string) =
echo data
template spawnAndSend(exprToSend: untyped) =
proc payload {.fauxClosure.} =
let data: string = exprToSend
sendSignal data
spawn payload()
proc getKey(self: Sob): int =
self.key
proc foo() =
echo $(myobject.sub.key)
# compiles and runs without error
foo()
# if uncommented Nim compiler fails with Error: 'spawn' takes a GC safe call expression
# spawn foo()
proc bar() =
echo $somenum
# compiles and runs without error
bar()
# compiles and runs without error
spawn bar()
proc baz(obj: Rob) =
echo $(obj.sub.key)
# compiles and runs without error
baz(myobject)
# `myobject` and `myobject.sub` are ref objects in the heap of the main thread,
# so why or why isn't that a problem/unsafe with respect to the spawned thread?
spawn baz(myobject)
# `myobject` and `myobject.sub` are ref objects in the heap of the main thread,
# so why or why isn't that a problem/unsafe with respect to the spawned thread?
proc quux() =
let sub = myobject.sub
spawnAndSend() do:
$(sub.getKey())
# compiles and runs without error
quux()
sleep(2)
# Run with `./env.sh nim c -r --threads:on --tlsEmulation:off foo.nim`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment