# 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:** 2

<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:58pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/21 "2022-10-31T12:58:12Z")

</div>

> [@tczajka](#):
>
> I don't understand what is "poor man's" about them.

Take a look at the [generators](https://doc.rust-lang.org/beta/unstable-book/language-features/generators.html#the-generator-trait). That's a more general syntax which backs the current async compiler, and which is aimed at general coroutines. In particular, you can have different types for `yield` and `return`, there is no `Poll::Pending` anywhere in sight (which doesn't make sense for coroutines), and there is also no `Waker` parameter (which exists specifically to efficiently handle blocking operations). You can also pass arbitrary data into the `Generator::resume` call, thus the coroutine has bidirectional communication with it its caller. Finally, you don't need any async runtime to deal with generators, they can be easily polled from a simple loop.

> [@tczajka](#):
>
> Because my code is asynchronous -- I want one function to wait for data from another function.

I mean, I don't know what exactly happens in your code, but in general it's easy to do using worker threads and channels between them. You should really consider whether you're not pulling in redundant complexity. One legitimate use case for async would be if you have something like an interaction with an embedded interpreter (like Lua or Julia) which cannot be interacted with from other threads.

> [@tczajka](#):
>
> 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).

They didn't say it "makes sense". They said "it generally only makes sense if ...". I read it as "can't stop you from using `tokio` this way, but at least try to limit the damage". They follow "Putting any network IO on the same runtime would be a pretty bad idea", and I/O is the primary reason to write async code. If you're not doing I/O, then likely you're using async as poor man's coroutines, as I said above.

It's likely that people use `tokio` this way just because they don't have any significantly better option, can't (or don't want) to write a special-purpose runtime for the coroutine case, and `tokio` is popular, while better-suited runtimes are not (you may already pull `tokio` for providing a web API).

---

<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, 1:38pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/22 "2022-10-31T13:38:39Z")

</div>

> [@afetisov](#):
>
> Take a look at the [generators](https://doc.rust-lang.org/beta/unstable-book/language-features/generators.html#the-generator-trait). [...] You can also pass arbitrary data into the `Generator::resume` call, thus the coroutine has bidirectional communication with it its caller.

That seems limiting. I want communication between different tasks via a channel, not just with the caller. Precisely what async await gives me.

> [@afetisov](#):
>
> mean, I don't know what exactly happens in your code, but in general it's easy to do using worker threads and channels between them.

I have thousands of tasks at the same time, with some finishing and new ones being created. I don't want the overhead of creating thousands of threads constantly and cooperative multitasking is perfect for me.

Isn't this what async is all about?

---

<div class="post-metadata">

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

</div>

I can only think of one reason to use an async runtime for CPU-bound computations, and I'm pretty sure that is not your use case. If you are every so often placing a `yield_now` in your CPU-bound function, that allows you to trivially cancel the computation based on an io-event. For example, if you are computing the next best move in a chess engine, you don't know if you may be able to finish some analysis at a specific depth, so you may want to abort if it isn't finished after some amount of time.

Other than that, `rayon` is definitely what you want. Yeah, tokio has a work stealing threadpool too, but it is just not meant for that.

---

<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, 1:52pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/24 "2022-10-31T13:52:54Z")

</div>

> [@afetisov](#):
>
> It's likely that people use `tokio` this way just because they don't have any significantly better option, can't (or don't want) to write a special-purpose runtime for the coroutine case, and `tokio` is popular, while better-suited runtimes are not (you may already pull `tokio` for providing a web API).

In what way exactly is tokio a bad runtime for this?

It may well be, I am curious. Maybe I **should** use or write a different runtime.

---

<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, 1:52pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/25 "2022-10-31T13:52:59Z")

</div>

> [@tczajka](#):
>
> I have thousands of tasks at the same time, with some finishing and new ones being created. I don't want the overhead of creating thousands of threads constantly and cooperative multitasking is perfect for me.

That sounds like you need a thread pool. Take a look at `rayon`'s [implementation](https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html).

---

<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, 1:57pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/26 "2022-10-31T13:57:54Z")

</div>

> [@tvallotton](#):
>
> Other than that, `rayon` is definitely what you want.

> [@afetisov](#):
>
> That sounds like you need a thread pool. Take a look at `rayon`'s [implementation](https://docs.rs/rayon/latest/rayon/struct.ThreadPool.html).

I believe that doesn't work. When a thread is stuck waiting for something, rayon is not going to reuse the thread to do some other work in the meantime. Or am I missing something?

---

<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, 2:07pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/27 "2022-10-31T14:07:36Z")

</div>

You'd have an even worse problem if an async task gets stuck waiting for something. You'd block the entire runtime's thread, and async runtimes typically use either a single thread, or thread per core.

With a thread pool, you can have a thousand simultaneous threads. If one of them is stuck, it shouldn't be a big deal. And didn't you say above that you have no issue of a thread sleeping for a while?

By the way, note that async runtimes also use a thread pool, to implement non-blocking calls of blocking system functions. You may get the same issue of all threads in a pool waiting for their syscall to complete, it's just way less likely.

---

<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, 2:16pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/28 "2022-10-31T14:16:52Z")

</div>

> [@afetisov](#):
>
> You'd have an even worse problem if an async task gets stuck waiting for something. You'd block the entire runtime's thread, and async runtimes typically use either a single thread, or thread per core.

No no, by "stuck waiting" I mean waiting for data from another task. I await on an async channel. This doesn't block the entire runtime.

> [@afetisov](#):
>
> With a thread pool, you can have a thousand simultaneous threads.

I could do that, but it seems unnecessary overhead if I only need as many threads as there are cpus.

> [@afetisov](#):
>
> And didn't you say above that you have no issue of a thread sleeping for a while?

Well in some cases, but not if it's a computation that will take a long time, in that case I don't want to waste cpu cycles waiting for that, I'd rather await and have the runtime pick another task to make progress on. If I block the thread, I might even deadlock forever!

---

<div class="post-metadata">

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

</div>

> [@tczajka](#):
>
> Maybe I **should** use or write a different runtime.

FWIW, [`switchyard`](https://docs.rs/switchyard/) is an existing async runtime specifically intended for compute workloads. (I have not yet tried using it for anything.)

---

<div class="post-metadata">

**Author:** ![mathstuf](https://avatars.discourse-cdn.com/v4/letter/m/958977/32.png) [@mathstuf](https://internals.rust-lang.org/u/mathstuf)\
**Post date:** [October 31, 2022, 4:32pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/30 "2022-10-31T16:32:42Z")

</div>

> [@afetisov](#):
>
> 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.

"Optimal" is a value decision. Rust should never stop someone from implementing bubble sort because quicksort exists.

> [@afetisov](#):
>
> 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.

For you, sure. But for others it might find other uses. See generators/coroutine use cases. And last I checked, neither you, me, nor any other single person here has the power to say what specific Rust features are "for".

---

<div class="post-metadata">

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

</div>

For example: to me, the biggest benefit of async is the possibility of `select!` — that _any combination of_ async operations (multiple event sources) can be combined as alternatives,\[1\] whereas when using plain threads in a complex application, you often have to create threads just to run specific blocking calls that offer no multiplexing and no timeout (which, in edge cases, might be effectively leaked if the event they are blocking on never happens).

This is orthogonal to whether async offers improved performance — it's about simplicity, composability, and correctness.

* * *

My take on the original topic: I think a good tool to introduce would be a lint that flags blocking calls in async. A lint is suitable because it is sometimes correct to ignore it (e.g. for a mutex where all uses are "fast" but still might technically block waiting for each other).

The problem with implementing this is that ideally the set of functions detected would be auto-trait-like: any `fn` that calls `thread::sleep` should _also_ count as a blocking function. This makes it a part of function signatures, increasing language complexity in a way we don't have a solution for yet.

* * *

1. (Cancellation safety is of course a problem which async _introduces_ here.)

---

<div class="post-metadata">

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

</div>

Please don't make normal functions panic unnecessarily. I've used `sleep()` in the past when testing and trying various things out. Even though it's not something I'd ever do in production, I'd be incredulous if `sleep()` panicked.

Use a linter or something less intrusive to detect unnecessary sleeps. But don't halt my program.

---

<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 31, 2022, 6:11pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/33 "2022-10-31T18:11:24Z")

</div>

> [@tczajka](#):
>
> I can think of a few reasonable cases where `thread::sleep` would be called from an `async` function. It should definitely not panic!

That's why I specified it should be able to be opted out locally. Outer contexts like latency optimized async runtime turn the flag on, but if you know this specific operation is ok to be blocked, just turn it off locally. But you should only do so if you know the problem and have considered about it enough.

> [@dead-claudia](#):
>
> 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`?

> [@hyeonu](#):
>
> With this change async runtimes can turn the flag while running its tasks.

> [@hyeonu](#):
>
> Make functions which are intended to be blocked panic early with good message if this flag is on.

They're clearly functions which are intended to be blocked. `Mutext::lock()` would be controversal, but I don't think it's expected to be blocked in happy path.

> [@kpreid](#):
>
> The problem with implementing this is that ideally the set of functions detected would be auto-trait-like: any `fn` that calls `thread::sleep` should _also_ count as a blocking function. This makes it a part of function signatures, increasing language complexity in a way we don't have a solution for yet.

True, it is (thread) global state affecting behavior significantly which is a big downside. I believe its benefit - to make common mistakes visible early - overcome its cost but people may disagree.

> [@mjbshaw](#):
>
> I've used `sleep()` in the past when testing and trying various things out. Even though it's not something I'd ever do in production

I think it's a good example why it should fail early by default but can be opt-out locally with more verbose API.

---

<div class="post-metadata">

**Author:** ![cpud36](https://avatars.discourse-cdn.com/v4/letter/c/94ad74/32.png) [@cpud36](https://internals.rust-lang.org/u/cpud36)\
**Post date:** [October 31, 2022, 7:53pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/34 "2022-10-31T19:53:22Z")

</div>

I have two conerns:

1. What if `std::thread::sleep` is buried deep down in the callstack?
2. What is the migration policy?

First, consider [kanal](https://docs.rs/kanal/0.1.0-pre4/kanal/). It provides fast sync and async channels. All its functions go through a lock, that may sleep([see source](https://github.com/fereidani/kanal/blob/main/src/mutex.rs#L51)).

How would one use e.g. `try_send` method? Does one needs to mess with the global flag around the call? Or is it a responsibility of the library author? What if the author does not care about async (so doesn't correctly raise the flag)?

Second, it is a breaking change to add panic to `std::thread::sleep`. At minimum it will definitely break `kanal` tests. Futhermore it might break some private code. So we cannot change what `std::thread::sleep` does.

We might try to deprecate `std::thread::sleep`, but it is complicated.

---

<div class="post-metadata">

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

</div>

> [@cpud36](#):
>
> First, consider [kanal](https://docs.rs/kanal/0.1.0-pre4/kanal/). It provides fast sync and async channels. All its functions go through a lock, that may sleep([see source](https://github.com/fereidani/kanal/blob/main/src/mutex.rs#L51)).

Does it call `thread::sleep` even when using the async channel?

---

<div class="post-metadata">

**Author:** ![cpud36](https://avatars.discourse-cdn.com/v4/letter/c/94ad74/32.png) [@cpud36](https://internals.rust-lang.org/u/cpud36)\
**Post date:** [November 1, 2022, 3:32pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/36 "2022-11-01T15:32:40Z")

</div>

> [@dlight](#):
>
> Does it call `thread::sleep` even when using the async channel?

Yes, it does. To be precise, there is only a single channel type, and `SyncSender` and `AsyncSender` are newtypes over shared [`Internal`](https://github.com/fereidani/kanal/blob/ac93742f47ce7ac6eb88969274e4e47f05f526a7/src/internal.rs#L11) channel data.

`try_send` is [defined here](https://github.com/fereidani/kanal/blob/ac93742f47ce7ac6eb88969274e4e47f05f526a7/src/lib.rs#L754) and [implemented here](https://github.com/fereidani/kanal/blob/ac93742f47ce7ac6eb88969274e4e47f05f526a7/src/lib.rs#L247). This function always [acquires the mutex](https://github.com/fereidani/kanal/blob/ac93742f47ce7ac6eb88969274e4e47f05f526a7/src/lib.rs#L265), which in turn may sleep under high contention.

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [November 1, 2022, 5:15pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/37 "2022-11-01T17:15:16Z")

</div>

> [@tczajka](#):
>
> I believe that doesn't work. When a thread is stuck waiting for something, rayon is not going to reuse the thread to do some other work in the meantime. Or am I missing something?

That depends on _how_ it got stuck. If it's a rayon blocking call, like waiting for the second half of a `join` to complete, then yes the thread will go into work-stealing in the meantime. But if it blocks on something outside of rayon, like I/O or `thread::sleep`, then you're just blocked -- rayon doesn't have any opportunity to preempt that.

---

<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:** [November 1, 2022, 5:42pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/38 "2022-11-01T17:42:24Z")

</div>

> [@cuviper](#):
>
> That depends on _how_ it got stuck. If it's a rayon blocking call, like waiting for the second half of a `join` to complete, then yes the thread will go into work-stealing in the meantime. But if it blocks on something outside of rayon, like I/O or `thread::sleep`, then you're just blocked -- rayon doesn't have any opportunity to preempt that.

Basically in my use case I want to pipeline my computation. I use channels (multi-consumer channels specifically). It might look something like this:

Task n:

- compute compute
- let a = output of task n-3 (wait)
- compute compute
- let b = output of task n-2 (wait)
- compute compute
- let c = output of task n-1 (wait)
- compute compute
- broadcast the output of task n

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [November 1, 2022, 5:52pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/39 "2022-11-01T17:52:50Z")

</div>

If you want rayon to stay busy during those waits, we would need some kind of rayon-enhanced channel. There's also a deadlock risk though -- if task X blocks and work-steals task Y, which needs X's output, then they'll be in the wrong order on the stack and unable to complete. We don't have a good design to avoid this kind of problem yet...

---

<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:** [November 1, 2022, 5:54pm UTC](https://internals.rust-lang.org/t/make-thread-sleep-panic-in-async-context/17645/40 "2022-11-01T17:54:51Z")

</div>

Isn't async exactly the mechanism designed to solve all these problems? There are async-enhanced channels, and async runtime's job is to make sure that those tasks that are not stuck get to run next.

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

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