tomo/api/channels.md
2024-08-18 20:00:21 -04:00

2.2 KiB

Channels

Channels are a thread-safe message queue for communicating between threads, although they can also be used as a general-purpose queue.

Syntax

The syntax to create a channel is |T|, where T is the type that will be passed through the channel. You can also specify a maximum size for the channel, which will cause pushing to block until the recipient has popped from the channel if the maximum size is reached.

channel := |Int|
channel:push(10)
channel:push(20)
>> channel:pop()
= 10
>> channel:pop()
= 20

small_channel := |Int; max_size=5|

Channel Methods

push

Description:
Adds an item to the channel.

Usage:

push(channel:|T|, item: T) -> Void

Parameters:

  • channel: The channel to which the item will be added.
  • item: The item to add to the channel.

Returns:
Nothing.

Example:

>> channel:push("Hello")

push_all

Description:
Adds multiple items to the channel.

Usage:

push_all(channel:|T|, items: [T]) -> Void

Parameters:

  • channel: The channel to which the items will be added.
  • items: The array of items to add to the channel.

Returns:
Nothing.

Example:

>> channel:push_all([1, 2, 3])

pop

Description:
Removes and returns an item from the channel. If the channel is empty, it waits until an item is available.

Usage:

pop(channel:|T|) -> T

Parameters:

  • channel: The channel from which to remove an item.

Returns:
The item removed from the channel.

Example:

>> channel:pop()
= "Hello"

clear

Description:
Removes all items from the channel.

Usage:

clear(channel:|T|) -> Void

Parameters:

  • channel: The mutable reference to the channel.

Returns:
Nothing.

Example:

>> channel:clear()

view

Description:
Returns a list of all items currently in the channel without removing them.

Usage:

channel:view() -> [T]

Parameters:

  • channel: The channel to view.

Returns:
An array of items currently in the channel.

Example:

>> channel:view()
= [1, 2, 3]