Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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

Understanding multithreading


Now that we understand the different approaches for concurrency in Rust, we can start with the most basic one: creating threads. If you have previously used languages such as Java or C++, you will probably be familiar with the new Thread() syntax in the former or the std::thread in the latter. In both cases, you will need to specify some code that the new thread will run, and some extra information the thread will have. In both cases, you can start threads and wait for them to finish.

Creating threads

In Rust, things are similar to the C++ approach, where we have the std::thread module with the spawn() function. This function will receive a closure or a pointer to a function and execute it. It will return a handle to the thread, and we will be able to manage it from outside. Let's see how this works:

use std::thread;

fn main() {
    println!("Before the thread!");

    let handle = thread::spawn(|| {
        println!("Inside the thread!");
    });
    println!...
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