Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

channel: add wait_sendable #48071

Merged
merged 1 commit into from
Sep 26, 2024
Merged

channel: add wait_sendable #48071

merged 1 commit into from
Sep 26, 2024

Conversation

jkarneges
Copy link
Member

@jkarneges jkarneges commented Sep 26, 2024

There are some places where instead of asynchronously sending a value to a channel (sender.send(value).await), we asynchronously wait for the ability to send to a channel and then immediately send the value after:

sender.check_send().await;

// immediate send without await
sender.try_send(value);

This API allows the opportunity to defer certain processing until the moment of the actual send. The problem is its usage is a bit fiddly and error-prone. Notably, if the code waiting for the ability to send decides to give up waiting, or if it finishes waiting but then decides not to send anything, it needs to explicitly cancel the operation (sender.cancel()). Failing to cancel can lead to broken coordination when there are multiple senders waiting to send.

This PR introduces a simpler API:

let send: SendOnce = sender.wait_sendable().await;
send.try_send(value);

If the future returned by wait_sendable() is dropped before completion, the operation is automatically canceled. If it completes, it produces a SendOnce struct which can be used to send up to one value via its try_send() method. If the SendOnce is dropped without sending anything, the operation is automatically canceled. Basically it makes the API hard to misuse.

Note that the method is named try_send() and not send() because the channel could still become full after obtaining the SendOnce, if another sender were to send to the channel.

This PR also uses the new API in a couple of places.

@jkarneges jkarneges force-pushed the jkarneges/wait-sendable branch from 0e8debb to 6549797 Compare September 26, 2024 01:07
@jkarneges jkarneges force-pushed the jkarneges/wait-sendable branch from 6549797 to d2cd444 Compare September 26, 2024 01:24
@jkarneges jkarneges merged commit c2c0244 into main Sep 26, 2024
19 checks passed
@jkarneges jkarneges deleted the jkarneges/wait-sendable branch September 26, 2024 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants