Module eco.channel
Coroutine channel.
A channel provides a mechanism for communication between coroutines by sending and receiving values.
- If the channel buffer is full, channel:send blocks until a receiver
consumes an item (or
timeoutexpires). - If the channel buffer is empty, channel:recv blocks until a sender
provides an item (or
timeoutexpires). - After channel:close, receivers can still drain buffered items, but sending will raise an error.
All timeouts are expressed in seconds.
Functions
| new ([capacity=1]) | Create a channel. |
Class channel
| channel:length () | Get the number of buffered items. |
| channel:close () | Close the channel. |
| channel:send (v[, timeout]) | Send a value to the channel. |
| channel:recv ([timeout]) | Receive a value from the channel. |
Functions
- new ([capacity=1])
-
Create a channel.
If
capacityis not provided or is less than 1, it defaults to 1.Parameters:
- capacity integer Buffer capacity (number of values). (default 1)
Returns:
-
channel
ch Channel instance.
Usage:
local channel = require 'eco.channel' local ch = channel.new(5) ch:send('hello') print(ch:recv())
Class channel
Channel object returned by channel.new.
- channel:length ()
-
Get the number of buffered items.
Returns:
-
int
Number of buffered values.
- channel:close ()
-
Close the channel.
This is idempotent.
After closing, channel:recv returns
nilonce the buffer is drained. channel:send will raise an error. - channel:send (v[, timeout])
-
Send a value to the channel.
Parameters:
- v any Value to send.
- timeout number Timeout in seconds. (optional)
Returns:
-
boolean
true On success.
Or
- nil On timeout.
-
string
Error message (
'timeout').
Raises:
If the channel is closed. - channel:recv ([timeout])
-
Receive a value from the channel.
If the channel is closed and the buffer is empty, returns
nil. On timeout, returnsnil, 'timeout'.Parameters:
- timeout number Timeout in seconds. (optional)
Returns:
-
any
v Received value.
Or
- nil On closed (and buffer drained) or timeout.
-
string
Error message (
'timeout') on timeout.