Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Memory and Concurrency

Threads, Channels and Locks in Nim

Learn how Nim creates threads, passes messages through channels, protects shared data with locks and atomics, and avoids data races, with pthread C stand-ins.

Nim has real operating system threads. Threads let a program use several CPU cores at once, but they also introduce data races, where two threads change the same memory without coordination. Nim's design pushes you toward message passing (copy data between threads) and gives you locks and atomics for the cases where sharing is needed.

Compile with --threads:on (the default since Nim 2). The real compiler is not available on this site, so the Nim code is read-only and the stand-ins use POSIX threads, which Nim's thread library wraps.

Spawning a thread

NIM
import std/os

var worker: Thread[int]

proc greet(id: int) {.thread.} =
  sleep(10)
  echo "hello from ", id

createThread(worker, greet, 7)
joinThread(worker)         # wait for it to finish

A thread procedure carries the {.thread.} pragma. It takes one argument (use a tuple or object for several) and cannot touch ordinary global variables, because the compiler's gcsafe analysis forbids unprotected global state. This rule removes a large class of data races at compile time.

C C stand-in: create and join a thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Channels: message passing

A Channel[T] is a thread-safe queue. One thread sends, another receives; the message is copied (or moved), so no memory is shared.

NIM
var ch: Channel[int]
ch.open()

proc producer() {.thread.} =
  for i in 1 .. 3: ch.send(i * i)

var t: Thread[void]
createThread(t, producer)
for _ in 1 .. 3:
  echo ch.recv()        # 1, 4, 9 in order
joinThread(t)
ch.close()

Channels are a good default: if each piece of data is owned by one thread at a time, there are no races. (In current Nim, std/channels and threadpool have changed over versions; check your version's documentation, and consider the taskpools or malebolgia packages for structured parallelism.)

The stand-in implements a one-slot mailbox with a mutex and a condition variable, the machinery inside a channel:

C C stand-in: a one-slot channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Sharing with locks

When threads must update the same value, protect it with a Lock. Shared globals use the {.guard.} pragma so the compiler checks that the lock is held.

NIM
import std/locks

var
  lock: Lock
  counter {.guard: lock.}: int

initLock(lock)

proc addMany() {.thread.} =
  for _ in 1 .. 1000:
    withLock lock:
      inc counter

withLock is a template that locks, runs the block and always unlocks. For a single integer, std/atomics (Atomic[int], fetchAdd) avoids a lock entirely.

The data race, shown

Without protection, counter++ is three steps (read, add, write) and updates get lost. The stand-in uses a mutex, which makes the answer exact:

C C stand-in: a mutex makes the count exact

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Remove the lock calls and the result will usually fall short of 20000 on a multi-core machine; the exact value varies, which is why races are so hard to debug.

Choosing a model

  • Many small I/O tasks: async/await, one thread.
  • CPU-heavy independent jobs: threads and channels, or a task pool package.
  • Shared counters or flags: atomics.
  • Shared structures: a lock around the whole operation, kept short.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pragma marks a thread procedure?

    createThread requires a proc marked {.thread.}.
  2. 2. Why prefer channels to shared variables?

    Each message has one owner at a time.
  3. 3. What does withLock guarantee?

    As a template it locks, runs the body and unlocks reliably.
  4. 4. What is a data race?

    Concurrent unsynchronized access with a write gives unpredictable results.

Summary

  • Threads use createThread, {.thread.} and joinThread.
  • Channels pass messages; the compiler's gcsafe analysis blocks unprotected globals.
  • Locks and atomics protect shared state.
  • Keep critical sections short; prefer message passing.

Next: Async and Await