Book Image

Rust High Performance

By : Iban Eguia Moraza
Book Image

Rust High Performance

By: Iban Eguia Moraza

Overview of this book

This book teaches you how to optimize the performance of your Rust code so that it is at the same level as languages such as C/C++. You'll understand and fi x common pitfalls, learn how to improve your productivity by using metaprogramming, and speed up your code. You will master the features of the language, which will make you stand out, and use them to greatly improve the efficiency of your algorithms. The book begins with an introduction to help you identify bottlenecks when programming in Rust. We highlight common performance pitfalls, along with strategies to detect and resolve these issues early. We move on to mastering Rust's type system, which will enable us to optimize both performance and safety at compile time. You will learn how to effectively manage memory in Rust, mastering the borrow checker. We move on to measuring performance and you will see how this affects the way you write code. Moving forward, you will perform metaprogramming in Rust to boost the performance of your code and your productivity. Finally, you will learn parallel programming in Rust, which enables efficient and faster execution by using multithreading and asynchronous programming.
Table of Contents (19 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

Moving data between threads


We saw with the Send and Sync traits that the first one allows for a variable to be sent between threads, but how does that work? Can we just use a variable created in the main thread inside our secondary thread? Let's try it:

use std::thread;

fn main() {
    let my_vec = vec![10, 33, 54];

    let handle = thread::Builder::new()
        .name("my thread".to_owned())
        .spawn(|| {
            println!("This is my vector: {:?}", my_vec);
        })
        .expect("could not create the thread");

    if handle.join().is_err() {
        println!("Something bad happened :(");
    }
}

What we did was create a vector outside the thread and then use it from inside. But it seems it does not work. Let's see what the compiler tells us:

That's interesting. The compiler noticed that the my_vec binding would be dropped at the end of the main() function, and that the inner thread could live longer. This is not the case in our example, since we join() both threads before...