Module channels

Channel support for threads. 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.

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.


Channel* {...}{.gcsafe.}[TMsg] = RawChannel
a channel for thread communication


proc send*[TMsg](c: var Channel[TMsg]; msg: TMsg) {...}{.inline.}
sends a message to a thread. msg is deeply copied.
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.
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 to avoid the blocking.
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).
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 instead.
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.
proc close*[TMsg](c: var Channel[TMsg])
closes a channel c and frees its associated resources.
proc ready*[TMsg](c: var Channel[TMsg]): bool
returns true iff some thread is waiting on the channel c for new messages.

© 2006–2018 Andreas Rumpf
Licensed under the MIT License.