Channel support for threads.
Note: This is part of the system module. Do not import it directly. To activate thread support compile with the --threads:on command line switch.
Note: Channels are designed for the Thread type. They are unstable when used with spawn
Note: The current implementation of message passing does not work with cyclic data structures.
Note: Channels cannot be passed between threads. Use globals or pass them by ptr.
Procs
proc send*[TMsg](c: var Channel[TMsg]; msg: TMsg) {...}{.inline.}
- Sends a message to a thread. msg is deeply copied. Source Edit
proc trySend*[TMsg](c: var Channel[TMsg]; msg: TMsg): bool {...}{.inline.}
-
Tries to send a message to a thread.
msg is deeply copied. Doesn't block.
Returns false if the message was not sent because number of pending items in the channel exceeded maxItems.
Source Edit proc recv*[TMsg](c: var Channel[TMsg]): TMsg
-
Receives a message from the channel c.
This blocks until a message has arrived! You may use peek proc to avoid the blocking.
Source Edit proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, msg: TMsg]
-
Tries to receive a message from the channel c, but this can fail for all sort of reasons, including contention.
If it fails, it returns (false, default(msg)) otherwise it returns (true, msg).
Source Edit proc peek*[TMsg](c: var Channel[TMsg]): int
-
Returns the current number of messages in the channel c.
Returns -1 if the channel has been closed.
Note: This is dangerous to use as it encourages races. It's much better to use tryRecv proc instead.
Source Edit proc open*[TMsg](c: var Channel[TMsg]; maxItems: int = 0)
-
Opens a channel c for inter thread communication.
The send operation will block until number of unprocessed items is less than maxItems.
For unlimited queue set maxItems to 0.
Source Edit proc close*[TMsg](c: var Channel[TMsg])
- Closes a channel c and frees its associated resources. Source Edit
proc ready*[TMsg](c: var Channel[TMsg]): bool
- Returns true iff some thread is waiting on the channel c for new messages. Source Edit