8000 docs: `block_on` should mention `block_in_place` · Issue #7387 · tokio-rs/tokio · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
docs: block_on should mention block_in_place #7387
Open
@BatmanAoD

Description

@BatmanAoD

Is your feature request related to a problem? Please describe.

As described in #5843, it's possible to run an async function from within a non-async context by combining Handle::block_on with task::block_in_place.

This is mentioned in the documentation for block_in_place, but not in the documentation for block_on or in the "Bridging with sync code" documentation. Additionally, the panic message when you attempt to use Handle::block_on without block_in_place does not point the user toward any solution:

This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks

"Driving asynchronous tasks" is (often) exactly why the user is invoking Handle::block_on, so this feels like a bit of a dead end, and googling the issue leads to threads such as this one about incorrect usage of #[tokio::main] (i.e. a tangentially-related issue).

It also appears to be possible to work around this issue using futures::executor::block_on; given a handle: Handle, this runs without panicking:

let _guard = handle.enter();
futures::executor::block_on(async { <some async code> });

...but it's confusing that this version of block_on behaves differently from Tokio's block_on methods, so Tokio users may want to know that the "native" Tokio equivalent relies on block_in_place.

Describe the solution you'd like

The doc-comments for Handle::block_on (and possibly Runtime::block_on) should mention block_in_place for use when all of the following are true (though I may be missing some requirements; see "additional context"):

  • the user wants to call async code from a sync context
  • the current thread may be the primary Tokio scheduler thread
  • the current Tokio runtime is multithreaded

This should also be mentioned in the "Bridging with sync code" documentation.

Describe alternatives you've considered

It may be worth mentioning block_in_place in the "cannot spawn runtime within runtime" message, in case the user is trying to call async code from a sync context.

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-tokioArea: The main tokio crateC-feature-requestCategory: A feature request.M-runtimeModule: tokio/runtimeT-docsTopic: documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0