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

Mention that drop is not called for statically spawned tasks #312

Merged
merged 1 commit into from
Jun 9, 2024

Conversation

notgull
Copy link
Member

@notgull notgull commented Jun 9, 2024

Closes #294

@notgull notgull merged commit 2e3dfc7 into master Jun 9, 2024
13 checks passed
@notgull notgull deleted the notgull/drop branch June 9, 2024 23:41
@notgull notgull mentioned this pull request Jun 15, 2024
@taiki-e
Copy link
Collaborator

taiki-e commented Jun 15, 2024

This is an issue that can generally be well handled by using a oneshot pattern, right? If so, it would be nice to mention it.

@notgull
Copy link
Member Author

notgull commented Jun 15, 2024

This is an issue that can generally be well handled by using a oneshot pattern, right?

Could you elaborate on what you mean by "oneshot pattern"?

@taiki-e
Copy link
Collaborator

taiki-e commented Jun 15, 2024

"oneshot pattern"

That may not have been the official name, but I meant usage of channels like the first example of https://docs.rs/tokio/latest/tokio/sync/oneshot/index.html#examples.

@notgull
Copy link
Member Author

notgull commented Jun 20, 2024

I'm sorry, I'm not sure I understand you. What do you mean by "oneshot pattern", and can we provide an example of using this pattern in the docs?

@taiki-e
Copy link
Collaborator

taiki-e commented Jun 20, 2024

I thought the code that had the problem is like the following code with println replaced by drop,

#[tokio::main]
async fn main() {
  tokio::spawn(async {
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    println!("this may or may not be shown");
  });
}

playground

However, you can use oneshot channel (or doing the equivalent with a normal channel) to force the program not to exit until the task is finished.

#[tokio::main]
async fn main() {
  let (s, r) = tokio::sync::oneshot::channel();
  tokio::spawn(async {
    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    println!("this always be shown");
    let _ = s.send(());
  });
  let _ = r.await;
}

playground

I personally called such a pattern "oneshot pattern", but I don't know if that was an idiomatic term. I'm sorry for confusing by using it.

(I used tokio in example since smol is unavailable on playground, but the same pattern should be available using single-capacity channel of async-channel.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

Destructors aren't run for detached tasks
2 participants