This module only works with --gc:arc or --gc:orc.
Warning:
This module is experimental and its interface may change.
The following is a simple example of two different ways to use channels: blocking and non-blocking.
Example: cmd: --threads:on --gc:orc
import std/channels import std/os # In this example a channel is declared at module scope. # Channels are generic, and they include support for passing objects between # threads. # Note that isolated data passed through channels is moved around. var chan = newChannel[string]() # This proc will be run in another thread using the threads module. proc firstWorker() = chan.send("Hello World!") # This is another proc to run in a background thread. This proc takes a while # to send the message since it sleeps for 2 seconds (or 2000 milliseconds). proc secondWorker() = sleep(2000) chan.send("Another message") # Launch the worker. var worker1: Thread[void] createThread(worker1, firstWorker) # Block until the message arrives, then print it out. let dest = chan.recv() assert dest == "Hello World!" # Wait for the thread to exit before moving on to the next example. worker1.joinThread() # Launch the other worker. var worker2: Thread[void] createThread(worker2, secondWorker) # This time, use a non-blocking approach with tryRecv. # Since the main thread is not blocked, it could be used to perform other # useful work while it waits for data to arrive on the channel. var messages: seq[string] while true: var msg = "" if chan.tryRecv(msg): messages.add msg # "Another message" break messages.add "Pretend I'm doing useful work..." # For this example, sleep in order not to flood stdout with the above # message. sleep(400) # Wait for the second thread to exit before cleaning up the channel. worker2.joinThread() # Clean up the channel. assert chan.close() assert messages[^1] == "Another message" assert messages.len >= 2
Consts
nimChannelCacheSize = 100
- Source Edit
Procs
proc `=copy`[T](dest: var Channel[T]; src: Channel[T])
- Shares Channel by reference counting. Source Edit
proc `=destroy`[T](c: var Channel[T])
- Source Edit
proc freeChannelCache() {....raises: [], tags: [].}
- Frees the entire channel cache, including all channels Source Edit
proc newChannel[T](elements = 30): Channel[T]
- Returns a new Channel. elements should be positive. elements is used to specify whether a channel is buffered or not. If elements = 1, the channel is unbuffered. If elements > 1, the channel is buffered. Source Edit
func send[T](c: Channel[T]; src: sink Isolated[T]) {.inline.}
- Sends item to the channel(blocking). Source Edit