How to read global data from a thread in Nim

Can you read global data from a thread in Nim? Yes you can, but currently you have to use pointers to do so. This is due to the way memory access from threads is protected by the compiler (with the default garbage-collection).

Here is an example:

import locks
import tables

var
  threads: array[4, Thread[void]]
  lock: Lock
  globalData = {"1": "one"}.toTable
  globalPtr = addr(globalData)

proc threadFunc() {.thread.} =
    acquire(lock) # lock stdout

    let data = cast[ptr Table[string,string]](globalPtr)[]
    echo data["1"]

    release(lock)

initLock(lock)

for i in 0..high(threads):
  createThread(threads[i], threadFunc)

joinThreads(threads)

You can build this code with:

nim c -d:debug --threads:on pointers.nim

This was tested with Nim v1.2.

This code was adapted from a threading example in the Nim docs.

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.