Hello guys! I need your help, cannot figure out wtf is going on here.
I made a minimal example which produces an "out of memory" error. The idea is
simple: create a "spawn" proc which
1. accepts a name (just a string)
2. runs some dumb thread
3. adds mapping to shared table: name -> thread
Since I use shared table, each thread can (safely, due to lock) access other
thread information using thread's name.
Here is the code:
import sharedtables
import strformat
import os
import typetraits
type
ThreadName = string
ThreadInfo = object
thread: Thread[ThreadName]
# ... and some other info (channel etc)
var threads: SharedTable[ThreadName, ThreadInfo]
threads.init()
proc threadEntrypoint(name: ThreadName) {.thread.} =
echo &"Inside thread: name={name}"
proc spawn(name: ThreadName) =
echo &"Spawning: name={name}"
threads.withKey(name) do (key: ThreadName, value: var ThreadInfo,
pairExists: var bool):
if pairExists:
raise newException(ValueError, "Thread with this name was already
registered")
echo &"withKey: name={key}"
value = ThreadInfo()
echo &"Creating thread: name={key}"
value.thread.createThread(param=key, tp=threadEntrypoint)
echo &"Created thread: name={key}"
pairExists = true
when isMainModule:
spawn(name="a")
sleep(1000)
Run
The output is really surprising, I cant google something similar and it's even
not an exception:
Spawning: name=a
withKey: name=a
Creating thread: name=a
Created thread: name=a
out of memory
Run
It's probably something related to shared table lock and spawning a thread
during this lock (but im not sure). I tried different ways to fill that shared
table with spawned threads but didn't succeed.