Module threads

Thread support for Nim. Note: This is part of the system module. Do not import it directly. To activate thread support you need to compile with the --threads:on command line switch.

Nim's memory model for threads is quite different from other common programming languages (C, Pascal): Each thread has its own (garbage collected) heap and sharing of memory is restricted. This helps to prevent race conditions and improves efficiency. See the manual for details of this memory model.

Example:

import locks

var
  thr: array[0..4, Thread[tuple[a,b: int]]]
  L: Lock

proc threadFunc(interval: tuple[a,b: int]) {.thread.} =
  for i in interval.a..interval.b:
    acquire(L) # lock stdout
    echo i
    release(L)

initLock(L)

for i in 0..high(thr):
  createThread(thr[i], threadFunc, (i*10, i*10+5))
joinThreads(thr)

Types

SysThread* = Handle
  Source Edit
Thread* {.
pure, final
.}[TArg] = object of GcThread when TArg is void: dataFn: proc () {.
nimcall, gcsafe
.} else: dataFn: proc (m: TArg) {.
nimcall, gcsafe
.} data: TArg
Nim thread. A thread is a heavy object (~14K) that must not be part of a message! Use a ThreadId for that.   Source Edit
ThreadId*[TArg] = ptr Thread[TArg]
the current implementation uses a pointer as a thread ID.   Source Edit

Procs

proc running*[TArg](t: Thread[TArg]): bool {.
inline
.}
returns true if t is running.   Source Edit
proc handle*[TArg](t: Thread[TArg]): SysThread {.
inline
.}
returns the thread handle of t.   Source Edit
proc joinThread*[TArg](t: Thread[TArg]) {.
inline
.}
waits for the thread t to finish.   Source Edit
proc joinThreads*[TArg](t: varargs[Thread[TArg]])
waits for every thread in t to finish.   Source Edit
proc createThread*[TArg](t: var Thread[TArg];
                        tp: proc (arg: TArg) {.
thread, nimcall
.}; param: TArg)
creates a new thread t and starts its execution. Entry point is the proc tp. param is passed to tp. TArg can be void if you don't need to pass any data to the thread.   Source Edit
proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural)
pins a thread to a CPU. In other words sets a thread's affinity. If you don't know what this means, you shouldn't use this proc.   Source Edit
proc createThread*(t: var Thread[void]; tp: proc () {.
thread, nimcall
.})
  Source Edit
proc threadId*[TArg](t: var Thread[TArg]): ThreadId[TArg] {.
inline
.}
returns the thread ID of t.   Source Edit