esp-rs / esp-idf-svc

Type-Safe Rust Wrappers for various ESP-IDF services (WiFi, Network, Httpd, Logging, etc.)
https://docs.esp-rs.org/esp-idf-svc/
Apache License 2.0
333 stars 183 forks source link

Use `std::thread::park` in examples? #453

Closed victorbnl closed 4 months ago

victorbnl commented 4 months ago

In some examples where a service needs to run in background (e.g. http_server.rs) and not be dropped at the return of main, core::mem::forget is used. I find it rather dirty as it just throws the service into the memory in a lingering, unreachable state. Instead, we could use std::thread::park, which makes main never return so the server does not go out of scope, but without blocking the code.

fn main() {
  let _service = …;
  std::thread::park();
}

I’m asking here to see if it’s a good idea as I’m a beginner in Rust, but if you agree I’ll make a pull request.

ivmarkov commented 4 months ago

In some examples where a service needs to run in background (e.g. http_server.rs) and not be dropped at the return of main, core::mem::forget is used. I find it rather dirty as it just throws the service into the memory in a lingering, unreachable state. Instead, we could use std::thread::park, which makes main never return so the server does not go out of scope, but without blocking the code.

fn main() {
  let _service = …;
  std::thread::park();
}

I’m asking here to see if it’s a good idea as I’m a beginner in Rust, but if you agree I’ll make a pull request.

I'm fine either way, and in the end maybe not so important, because threads on embedded are so expensive, that it is unlikely that anybody would abandon its main thread lingering around (as std::thread:park does) and occupying stack space. Some examples also do std::thread:sleep in a loop which is essentially equivalent to std::thread::park.

By the way, I've not used std::thread::park, but by looking into its documentation, it is unclear to me if you can just call std::thread::park and it will stay parked forever. I.e. is it amenable to spurious wakeups? If you, you have to wrap it in a loop {}.

Yes, you can open a PR if you feel strongly about core::mem::forget though the latter is not necessarily bad. And is completely safe.

victorbnl commented 4 months ago

You are right. I had completely overseen that, and in that case it is way better to just detach the threads by forgetting the objects. I am going to switch to using that behaviour in my project too.