# Make thread::sleep() panic in async context

**URL:** <https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645>\
**Category:** libs\
**Created:** [October 29, 2022, 4:43am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645 "2022-10-29T04:43:18Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![hyeonu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hyeonu/32/2162_2.png) [@hyeonu](https://internals.rust-lang.org/u/hyeonu)\
**Post date:** [October 29, 2022, 4:43am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/1 "2022-10-29T04:43:18Z")

</div>

Calling `thread::sleep()` in async context is bad, we should fail it by default. Or should we?

It's common for beginners (for the async or the Rust in general) to call some blocking functions in async context and wonder why it's messed up without any clue. Ideally those functions should return `Err` instantly which describes that this function should not be called in this context, unless the caller explicitly passed some `i_know_what_im_doing_now` flag. But it's too late to _fix_ those function signatures. The only way remaining to blame caller is panicking.

What I want to propose is:

1. Expose a new thread local flag from stdlib with some scary named APIs which is off by default.
2. Declare that modifying this flag is a breaking change.
3. Make functions which are intended to be blocked panic early with good message if this flag is on. Consider it's not a breaking change.

With this change async runtimes can turn the flag while running its tasks. Some advanced use cases may expliticly turn the flag off during its specific operation.

I know, it sounds pretty dangerous. And that's why I omitted anything subject to bikeshed here. Should we do this? What do you think?

---

<div class="post-metadata">

**Author:** ![Neutron3529](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/neutron3529/32/6976_2.png) [@Neutron3529](https://internals.rust-lang.org/u/Neutron3529)\
**Post date:** [October 29, 2022, 9:10am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/2 "2022-10-29T09:10:08Z")

</div>

use lint, it could raise an warning if you use `thread::sleep()` in async context.

panic does not solve the problem.

(I know custom lint could solve such problem, but I don't know how to define such custom lint.)

---

<div class="post-metadata">

**Author:** ![jbe](https://avatars.discourse-cdn.com/v4/letter/j/f6c823/32.png) [@jbe](https://internals.rust-lang.org/u/jbe)\
**Post date:** [October 29, 2022, 10:21am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/3 "2022-10-29T10:21:07Z")

</div>

> [@hyeonu](#):
>
> Calling `thread::sleep()` in async context is bad, […]

Is this always the case? I'm not sure. I could imagine some sort of co-routines where `async` isn't used for real "concurrency" but just to yield control flow. In such a context, truly sleeping might be desirable. But I haven't really thought this through.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [October 29, 2022, 2:25pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/4 "2022-10-29T14:25:59Z")

</div>

`thread::sleep()` isn't in any way worse than just hogging up a thread with a long intensive computation with no opportunity to yield. The latter is even easier. `thread::sleep` can at least be linted against project-wise using the `#![deny(clippy::disallowed_methods)]` lint.

---

<div class="post-metadata">

**Author:** ![hyeonu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hyeonu/32/2162_2.png) [@hyeonu](https://internals.rust-lang.org/u/hyeonu)\
**Post date:** [October 29, 2022, 2:58pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/5 "2022-10-29T14:58:30Z")

</div>

> [@Neutron3529](#):
>
> use lint, it could raise an warning if you use `thread::sleep()` in async context.

Lints would definitely improve the situation. It can't prevent every cases as it doesn't perform global analysis, but to prevent basic mistakes is really nice and possibly good enough so we don't need any runtime barriers like I proposed.

> [@Neutron3529](#):
>
> panic does not solve the problem.

Yes, panic does not solve problem. It only make problems visible and debuggable. That's why we recommend to `.unwrap()` instead of to ignore them and even have compiler warnings for unused `Result`s.

> [@jbe](#):
>
> I could imagine some sort of co-routines where `async` isn't used for real "concurrency" but just to yield control flow.

Unfortunately most popular async runtimes are not optimized for this use cases. It is bad for them. If you make another async runtime which is optimized on blocking operations, which would be really nice, you don't need to touch the "don't block" flag. If blocking is needed anyway, which should be considered as advanced use case I mentioned in original post, you can opt-out the flag.

> [@afetisov](#):
>
> `thread::sleep()` isn't in any way worse than just hogging up a thread with a long intensive computation with no opportunity to yield

Which also is bad like `thread::sleep()`. Only reason why `thread::sleep()` is worse is that it seems too simple, common and innocent. But general purpose async runtimes tend to behave weird on long blocking operations.

> [@afetisov](#):
>
> linted against project-wise using the `#![deny(clippy::disallowed_methods)]` lint.

What I'm focusing here is beginner experience. I can't expect them to follow instructions more than "run cargo clippy and fix all warnings". Whatever we do for them, it should be turned on by default and can be opt-out for advanced use cases. It would be nice if that lint is turned on by default on async context.

---

<div class="post-metadata">

**Author:** ![jbe](https://avatars.discourse-cdn.com/v4/letter/j/f6c823/32.png) [@jbe](https://internals.rust-lang.org/u/jbe)\
**Post date:** [October 29, 2022, 4:53pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/6 "2022-10-29T16:53:51Z")

</div>

> [@hyeonu](#):
>
> Unfortunately most popular async runtimes are not optimized for this use cases. It is bad for them.

You could elaborate on that? Is it due to the runtime(s)? Or due to their use cases?

What I mean is something like this:

```rust
async fn inner() {
    for i in 1..=3 {
        println!("step{i}");
        std::thread::sleep(std::time::Duration::from_millis(1000));
        my_little_runtime::yield_task(format!{"Hello {i}"}).await;
    }
}

async fn outer() {
    inner().await;
}

fn main() {
    my_little_runtime::run(outer(), || {
        // ideally I would somehow get the value passed to `yield_task` as an
        // argument here
        println!("yielded");
    });
}

```

([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3fa037cbfd93b6068a60a59e01e9072d))

My point is: Being in an `async` context doesn't necessarily mean that we're doing green-threading or something like that. Maybe it's just a coroutine with no concurrency at all.

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [October 29, 2022, 5:16pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/7 "2022-10-29T17:16:39Z")

</div>

> [@hyeonu](#):
>
> Unfortunately most popular async runtimes are not optimized for this use cases. It is bad for them.

But a runtime _can_ be. Futures in the language where designed around being mostly agnostic of runtimes, and there is no default runtime shipped with std. Making a std function _panic_ should only be done if it is wrong to use in _all_ runtimes, which it isn't. A more accurate design would be an extension point that involves the async runtime in `thread::sleep`, but I'm curious how one would find out if a function is inside an async context in the first place (to acquire some handle to the runtime)?

---

<div class="post-metadata">

**Author:** ![hyeonu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hyeonu/32/2162_2.png) [@hyeonu](https://internals.rust-lang.org/u/hyeonu)\
**Post date:** [October 29, 2022, 5:52pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/8 "2022-10-29T17:52:23Z")

</div>

> [@jbe](#):
>
> My point is: Being in an `async` context doesn't necessarily mean that we're doing green-threading or something like that.

> [@197g](#):
>
> But a runtime _can_ be

True. It's not a fundamental property of the async Rust, just a common property of popular runtimes (for good reasons of course). My original suggestion address this problem by not forcing async runtimes to set the flag. But the lint can't know if the runtime has such property which makes this approach less appealing...

> [@jbe](#):
>
> You could elaborate on that? Is it due to the runtime(s)? Or due to their use cases?

It's mainly because they're userland thread scheduler. OS schedulers do its maintenance works regularly by freezing currently-running thread via interrupt. But userland async schedulers can only do so on `.await` point. It's worth mentioning that many of them are highly influenced by the Go runtime which can trust its compiler automatically insert await points regularly during compilation.

---

<div class="post-metadata">

**Author:** ![toc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/toc/32/6692_2.png) [@toc](https://internals.rust-lang.org/u/toc)\
**Post date:** [October 29, 2022, 6:42pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/9 "2022-10-29T18:42:54Z")

</div>

If/when keyword generics gets off the ground, it would be incredible to have a generic version of `thread::sleep` which chooses the correct version depending on context. It seems very likely that `thread::sleep` should continue do what it does (sleep the thread and not panic in any context), but in the case that a generic version exists it can be easily linted towards.

Until then lints are probably the best we're going to get.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [October 31, 2022, 2:59am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/10 "2022-10-31T02:59:29Z")

</div>

Long computation at least does something productive and in some situations may be difficult to avoid. `thread::sleep` is just a mistake and a waste.

---

<div class="post-metadata">

**Author:** ![dead-claudia](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dead-claudia/32/6944_2.png) [@dead-claudia](https://internals.rust-lang.org/u/dead-claudia)\
**Post date:** [October 31, 2022, 3:43am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/11 "2022-10-31T03:43:00Z")

</div>

How do you plan to detect that a function is in fact called in an `async` context? Also, if we're doing `thread::sleep()`, why not `File::open`? Why not `TcpStream::write`? Why not `UdpSocket::send`? The list could go on pretty far.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [October 31, 2022, 9:20am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/12 "2022-10-31T09:20:39Z")

</div>

`thread::sleep` deschedules the current thread and allows other threads to run. It is an opposite of "waste", unless you're optimizing for latency.

In any case, it is very disruptive when functions panic for any reason. Plenty of code tries to enforce the no-panic approach. The last thing I want is to have perfectly reasonable stdlib functions suddenly start panicking.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [October 31, 2022, 11:32am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/13 "2022-10-31T11:32:36Z")

</div>

It's a waste also in terms of resource usage. It keeps OS threads occupied for pathologically long time in the async runtime, which means that the runtime will need to spawn more OS threads to remain responsive or will be starved of threads that can make progress in async tasks. On busy servers latency spikes/runtime stalls like this can cause work to pile up, which increases memory usage. Starved tasks can time out, which wastes work already done, and when these tasks are retried, it's more wasted effort. Besides, having decent latency in an async runtime is often important too, and lags are disruptive too.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [October 31, 2022, 11:40am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/14 "2022-10-31T11:40:31Z")

</div>

I can think of a few reasonable cases where `thread::sleep` would be called from an `async` function. It should definitely not panic!

An `async` function might call a non-async function that uses short `thread::sleep` as part of polling something -- coming from another thread, or from a device, etc. That function should definitely not stop working properly just because it's called from an `async` function further up the chain.

One might be using `thread::sleep` as a placeholder for a CPU-heavy computation that will be implemented later.

Somebody just learning Rust might be using `thread::sleep` for experiments to understand how things work.

Someone might want to put a whole single threaded async runtime on hold because there are better things for code to do in a different thread rather than doing the async stuff.

`thread::sleep` should do what it advertises, not panic.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [October 31, 2022, 11:54am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/15 "2022-10-31T11:54:57Z")

</div>

> [@kornel](#):
>
> On busy servers latency spikes/runtime stalls like this can cause work to pile up, which increases memory usage.

That's a specific scenario. Busy servers that are latency sensitive have certain constraints. Not all async code is for busy latency sensitive servers with many users. One shouldn't break basic functionality for everybody in order to help with debugging some specific use case.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [October 31, 2022, 11:59am UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/16 "2022-10-31T11:59:52Z")

</div>

> [@kornel](#):
>
> It's a waste also in terms of resource usage.

Those are all true, but that's also true for any kind of blocking call, and for any compute-intensive operation. Neither of those should be used inside of an async task, they should be delegated to a thread pool. `thread::sleep` isn't in any way worse than them.

> [@tczajka](#):
>
> An `async` function might call a non-async function that uses short `thread::sleep` as part of polling something

That's definitely a bug. You would block your async runtime entirely while that function waits for completion. It should be rewritten to use non-blocking calls. That's part of the problem: you need to track not only direct blocking calls inside of async blocks, but also any transitive calls through sync functions.

> [@tczajka](#):
>
> One might be using `thread::sleep` as a placeholder for a CPU-heavy computation that will be implemented later.

You shouldn't do CPU-heavy operations inside of async tasks, see above.

> [@tczajka](#):
>
> Somebody just learning Rust might be using `thread::sleep` for experiments to understand how things work.

Well, it's nice to experiment, but the topic started specifically with someone learning Rust and calling `thread::sleep` by mistake. It would be nice to avoid that error.

> [@tczajka](#):
>
> Someone might want to put a whole single threaded async runtime on hold because there are better things for code to do in a different thread rather than doing the async stuff.

There are valid reasons to stop a single-threaded runtime, but those decisions should be made by the runtime itself, which runs normal sync code. Putting blocking methods inside of async code is a violation of layering and a footgun. That said, the runtime may provide specific "sleep the runtime" calls for specific cases, that just shouldn't be the error-prone `thread::sleep`.

> [@tczajka](#):
>
> `thread::sleep` should do what it advertises, not panic.

On that point I agree. Adding panics is an API break, because your users may depend on lack of panics for correctness, and you silently change it from under them. Now, Rust gives precious little control over the lack of panics, but `thread::sleep` certainly doesn't have valid reasons to change its panic behaviour.

Overall, the issue of misused stdlib APIs is something which should be solved by Clippy lints, not changing the API from under its users.

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [October 31, 2022, 12:03pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/17 "2022-10-31T12:03:09Z")

</div>

One specific reason where one may want to make blocking calls in async code is where one uses the current async machinery as a poor man's substitute for proper coroutines, which are unsupported on current Rust. If I use `async` just as a way to access the state machine compiler, I don't care that the thread blocks (I would use different threads for different tasks anyway).

That said, that use case would certainly require a different runtime than `tokio` or `async-std` to run properly. Since the proposal is to give the runtime itself the option to set the panic flag, it is orthogonal.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [October 31, 2022, 12:03pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/18 "2022-10-31T12:03:44Z")

</div>

> [@afetisov](#):
>
> That's definitely a bug. You would block your async runtime entirely while that function waits for completion.

So what? Maybe I'm OK with blocking my async runtime while the function waits for completion. If that only takes 0.1% of my total computation time, that's perfectly fine.

> [@afetisov](#):
>
> It should be rewritten to use non-blocking calls.

So you're telling me I **have** to optimize my code, even if I don't care about the performance of this particular part because it doesn't bother me? That's not how optimization should work. What if that code is from some other library, and it works fine for me -- I **have to** rewrite the library because you're calling it "a bug"?

> [@afetisov](#):
>
> You shouldn't do CPU-heavy operations inside of async tasks, see above.

[Smart people disagree.](https://users.rust-lang.org/t/tokio-using-core-threads-for-cpu-heavy-computation/83443)

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [October 31, 2022, 12:10pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/19 "2022-10-31T12:10:31Z")

</div>

> [@tczajka](#):
>
> So you're telling me I **have** to optimize my code

If you don't care about optimization, then why are you writing async code? Async is basically an optimization for dealing with IO-bound tasks.

Part of the Rust's philosophy is to encourage correct and performant code at the language level. It shouldn't be easier to do a suboptimal thing than an optimal one.

> [@tczajka](#):
>
> Smart people disagree.

You have linked your question. Which part of that thread specifically is "smart people disagree"?

I mean, you can write all kind of weird code if you really want to. You can write a webserver [in Bash](https://funprojects.blog/2021/04/11/a-web-server-in-1-line-of-bash/), or in a Rust proc macro. Doesn't make it a good idea, or something that the language should support.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [October 31, 2022, 12:17pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/20 "2022-10-31T12:17:36Z")

</div>

> [@afetisov](#):
>
> One specific reason where one may want to make blocking calls in async code is where one uses the current async machinery as a poor man's substitute for proper coroutines

As far as I can tell, async implements standard coroutines. I don't understand what is "poor man's" about them.

> [@afetisov](#):
>
> If you don't care about optimization, then why are you writing async code?

Because my code is asynchronous -- I want one function to wait for data from another function.

I do care about performance, but that doesn't mean it's a bug if I don't optimize everything. I optimize the parts that are performance bottlenecks.

> [@afetisov](#):
>
> You have linked your question. Which part of that thread specifically is "smart people disagree"?

Alice, who I understand is a core tokio developer, said in that thread that running CPU-heavy computations in a Tokio run-time ["makes sense"](https://users.rust-lang.org/t/tokio-using-core-threads-for-cpu-heavy-computation/83443/8?u=tczajka), and that my use case is ["reasonable"](https://users.rust-lang.org/t/tokio-using-core-threads-for-cpu-heavy-computation/83443/13?u=tczajka).

[Next page](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645.md?page=2)
