Channels in Nim

Channels are the pipes that connect concurrent threads. You can send values into channels from one thread and receive those values into another thread.

import std/channels
import std/threadpool
import std/strformat

proc main() =
  # Create a new channel with `newChannel[T]()`.
  # Channels are typed by the values they convey.
  let messages = newChannel[string]()

  # Send a value into a channel using the `send()` method.
  # Here we send "ping" to the `messages` channel we made above, from a new thread.
  spawn do:
    messages.send("ping")

  # The `recv()` method receives a value from the channel.
  # Here we'll receive the "ping" message we sent above and print it out.
  let msg = messages.recv()
  echo msg

main()

When we run the program, the “ping” message is successfully passed from one thread to another via our channel.

$ nim c -r channels.nim
ping

By default, sends and receives block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization.

In Nim, we use the channels module to create and work with channels. The threadpool module provides the spawn macro for creating concurrent threads, which is similar to goroutines in concept. The send() and recv() methods are used for sending and receiving values through the channel, respectively.

Note that Nim’s approach to concurrency is slightly different from some other languages, but the core concept of using channels for communication between concurrent operations remains the same.