thread
thread
¶
Background threads and channels.
SDL, the GPU and all drawing are main-thread affairs, so threads here are for
work off to the side: loading files, decoding, generation. A thread runs a
top-level proc marked {.thread.}, and a channel passes messages between
threads. Messages are copied as they cross, so a value or a string travels
safely; share data through a channel rather than through globals you mutate.
A channel is usually a module-level global so both the worker proc and the main loop can name it, since a thread proc takes no captured state.
Channel2d
¶
type Channel2d[T] = object
A typed, thread-safe queue of messages. Make one with newChannel.
newThread ¶
proc newThread(fn: proc () {.thread, nimcall.}): Thread2d
Start a thread running fn. The proc must be a top-level {.thread.} proc,
not a closure, so it carries no captured variables.
Parameters
-
fn(proc () {.thread, nimcall.})
Returns
Thread2d
join ¶
proc join(t: Thread2d)
isRunning ¶
proc isRunning(t: Thread2d): bool
Whether the thread is still running.
Parameters
-
t(Thread2d)
Returns
bool
newChannel ¶
proc newChannel(): Channel2d[T]
Make an open channel carrying messages of type T.
Returns
Channel2d[T]
send ¶
proc send(c: Channel2d[T]; msg: sink T)
Send a message. A copy of the message crosses to the receiver.
Parameters
-
c(Channel2d[T]) -
msg(sink T)
receive ¶
proc receive(c: Channel2d[T]): T
Receive a message, blocking until one arrives.
Parameters
-
c(Channel2d[T])
Returns
T
tryReceive ¶
proc tryReceive(c: Channel2d[T]): tuple[received: bool, msg: T]
Receive a message if one is waiting, without blocking.
Parameters
-
c(Channel2d[T])
Returns
tuple[received: bool, msg: T]
peek ¶
proc peek(c: Channel2d[T]): int
How many messages are waiting (negative if the channel is closed).
Parameters
-
c(Channel2d[T])
Returns
int
close ¶
proc close(c: var Channel2d[T])
Close the channel and free it. Do this after the threads using it are done.
Parameters
-
c(var Channel2d[T])