Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Rust High Performance

You're reading from   Rust High Performance Learn to skyrocket the performance of your Rust applications

Arrow left icon
Product type Paperback
Published in Mar 2018
Publisher Packt
ISBN-13 9781788399487
Length 272 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Iban Eguia Moraza Iban Eguia Moraza
Author Profile Icon Iban Eguia Moraza
Iban Eguia Moraza
Arrow right icon
View More author details
Toc

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image