Waiting efficiently for a specific duration of time OR notification

Hi there!

I'm currently struggling to make the following thing:

I'd like to create a thread that performs a specific (very quick) action every second, but which can also be stopped at any moment during the waiting time from the parent thread.

How can I achieve this with maximum efficiency? I've tried so far:

  • Waiting 50 times for a duration of 20 milliseconds, checking at each iteration the value of an AtomicBool to check if the thread should be stopped, and if set exit properly ;
  • Setting up a Condvar, but as the docs state the amount of time is not precise, plus it's not designed for that usage.

Any idea on this?

I thought that Receiver::recv_timeout might be useful here, but looking at the source, it is implemented using thread::park_timeout, which has the same warnings as Condvar::wait_timeout. (The same is true of the corresponding method in the crossbeam-channel crate.)

How much precision do you need? You might want to test one of these “imprecise” methods to see how much well they work in practice. If you're okay being off by a small number of milliseconds, they might be good enough.

1 Like

Well <10 ms would be good enough. The main problem I have with Condvar is that it seems to be designed to be exclusively used with a Mutex<T>, which I don't have here.

You could create a Mutex<()> just for use with the Condvar. But I think using a channel (from std::sync::mpsc or crossbeam-channel) would probably be simpler.

1 Like

Ok, thanks a lot for your help ! :slight_smile: