"block_in_place" and blocking sleep, or async sleep
⚓ Rust 📅 2025-10-02 👤 surdeus 👁️ 7Howdy.
We're running some async task using Tokio and, having performed a write to a serial port for RS485, need to sleep until those characters are transmitted, plus a few ms more - generally around 10ms all-up.
Given a library we're using, this writer task is required to be async.
What might be the preferred approach to having a reasonably accurate sleep - should we use Tokio's block_in_place and std::thread::sleep, or just use Tokio's async sleep?
Here's the code in question with block_in_place, which is observed to work nicely:
// We block here as it is important that we wake up in time,
// and so we give ourselves the best chance.
tokio::task::block_in_place(|| {
    const BITS_PER_BYTE: u64 = 8;
    const START_BIT: u64 = 1;
    const STOP_BIT: u64 = 1;
    const BITS_PER_CHAR: u64 = BITS_PER_BYTE + START_BIT + STOP_BIT;
    let time_on_wire =
        Duration::from_millis(1000 * BITS_PER_CHAR * n as u64 / self.baud_rate as u64);
    std::thread::sleep(time_on_wire + self.enable_tx_flush_delay);
    self.disable_tx();
})
Thanks.
1 post - 1 participant
🏷️ Rust_feed