Last active
February 25, 2021 21:14
-
-
Save michaelsbradleyjr/c1118612952ca6efb273f4bb2d449f6d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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