Thread support for Nimrod. 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.
Nimrod'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, TThread[tuple[a,b: int]]] L: TLock 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
TThread* {.pure, final.}[TArg] = object of TGcThread when TArg is void: dataFn: proc () {.nimcall.} else: dataFn: proc (m: TArg) {.nimcall.} data: TArg
- Nimrod thread. A thread is a heavy object (~14K) that must not be part of a message! Use a TThreadId for that.
TThreadId*[TArg] = ptr TThread[TArg]
- the current implementation uses a pointer as a thread ID.
Procs
proc running*[TArg](t: TThread[TArg]): bool {.inline.}
- returns true if t is running.
proc joinThread*[TArg](t: TThread[TArg]) {.inline.}
- waits for the thread t to finish.
proc joinThreads*[TArg](t: varargs[TThread[TArg]])
- waits for every thread in t to finish.
proc createThread*[TArg](t: var TThread[TArg]; tp: proc (arg: TArg) {.thread.}; 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.
proc threadId*[TArg](t: var TThread[TArg]): TThreadId[TArg] {.inline.}
- returns the thread ID of t.
proc myThreadId*[TArg](): TThreadId[TArg]
- returns the thread ID of the thread that calls this proc. This is unsafe because the type TArg is not checked for consistency!