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)we need to cache current threadId to not perform syscall all the time
SysThread* = Handle
Thread* {...}{.pure, final.}[TArg] = object core: PGcThread sys: SysThread when TArg is void: dataFn: proc () {...}{.nimcall, gcsafe.} else: dataFn: proc (m: TArg) {...}{.nimcall, gcsafe.} data: TArg
proc onThreadDestruction*(handler: proc () {...}{.closure, gcsafe.})
.thread
proc returns normally or when it raises an exception. Note that unhandled exceptions in a thread nevertheless cause the whole process to die. proc running*[TArg](t: Thread[TArg]): bool {...}{.inline.}
proc handle*[TArg](t: Thread[TArg]): SysThread {...}{.inline.}
proc joinThread*[TArg](t: Thread[TArg]) {...}{.inline.}
proc joinThreads*[TArg](t: varargs[Thread[TArg]])
proc createThread*[TArg](t: var Thread[TArg]; tp: proc (arg: TArg) {...}{.thread, nimcall.}; param: TArg)
void
if you don't need to pass any data to the thread. proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural)
proc createThread*(t: var Thread[void]; tp: proc () {...}{.thread, nimcall.})
proc getThreadId*(): int
© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/threads.html