Search code examples
real-timerust

How do I do realtime programming in Rust?


I'm looking at Rust as a replacement for C/C++ in hard realtime programming. There are two possible issues I've identified:

1) How to I avoid invoking Rust's GC? I've seen suggestions that I can do this by simply avoiding managed pointers and non-realtime-safe libraries (such as Rust's standard library) -- is this enough to guarantee my realtime task will never invoke the GC?

2) How do I map my realtime task to an OS thread? I know Rust's standard library implements an N:M concurrency model, but a realtime task must correspond directly with one OS thread. Is there a way to spawn a thread of this type?


Solution

  • 1) How to I avoid invoking Rust's GC? I've seen suggestions that I can do this by simply avoiding managed pointers and non-realtime-safe libraries (such as Rust's standard library) -- is this enough to guarantee my realtime task will never invoke the GC?

    Yes, avoiding @ will avoid the GC. (Rust currently doesn't actually have the GC implemented, so all code avoids it automatically, for now.)

    2) How do I map my realtime task to an OS thread? I know Rust's standard library implements an N:M concurrency model, but a realtime task must correspond directly with one OS thread. Is there a way to spawn a thread of this type?

    std::task::spawn_sched(std::task::SingleThreaded, function) (the peculiar formatting will be fixed when #10095 lands), e.g.

    use std::task;
    fn main() {
        do task::spawn_sched(task::SingleThreaded) {
            println("on my own thread");
        }
    }
    

    That said, Rust's runtime & standard libraries aren't set up for hard-realtime programming (yet), but you can run "runtimeless" using #[no_std] (example) which gives you exactly the same situation as C/C++, modulo language differences and the lack of a standard library (although Rust's FFI means that you can call into libc relatively easily, and the rust-core project is designed to be a minimal stdlib that doesn't even require libc to work).