Channel Buffering in Nim

By default channels in Nim are unbuffered, meaning that they will only accept sends if there is a corresponding receive ready to receive the sent value. Buffered channels accept a limited number of values without a corresponding receiver for those values.

import std/channels

proc main() =
  # Here we create a channel of strings buffering up to 2 values.
  var messages = newChannel[string](2)

  # Because this channel is buffered, we can send these
  # values into the channel without a corresponding
  # concurrent receive.
  messages.send("buffered")
  messages.send("channel")

  # Later we can receive these two values as usual.
  echo messages.recv()
  echo messages.recv()

main()

To run the program:

$ nim c -r channel_buffering.nim
buffered
channel

In this Nim example, we’re using the channels module from the standard library to create a buffered channel. The newChannel[string](2) function creates a channel that can buffer up to 2 string values.

We then send two values into the channel using the send method. Because the channel is buffered, these sends can occur without an immediate corresponding receive.

Finally, we receive and print the two values from the channel using the recv method.

This demonstrates how buffered channels in Nim can be used to decouple send and receive operations, allowing for more flexible communication patterns between concurrent parts of a program.