Rust threading

From wikinotes
Revision as of 03:56, 10 February 2023 by Will (talk | contribs) (Created page with "= Documentation = <blockquote> {| class="wikitable" |- | rust book: concurrency || https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html |- |} </blockquote><!-- Documentation --> = Basics = <blockquote> Since rust already manages ownership semantics, you don't really need to deal with thread affinity.<br> Simply pass a closure to a thread, move any params to it, and call it a day. thead without outer scope access <syntaxhighlight lang="rust"> use std::thread;...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

rust book: concurrency https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html

Basics

Since rust already manages ownership semantics, you don't really need to deal with thread affinity.
Simply pass a closure to a thread, move any params to it, and call it a day.

thead without outer scope access

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..=5 {
            println!("step {}/5..", i);
            thread::sleep(Duration::from_secs(1));
        }
    });
    handle.join().expect("unable to join thread");
}

thread that moves outer-scope into thread's closure

use std::thread;
use std::time::Duration;

fn main() {
    let name = String::from("alex");
    let handle = thread::spawn(move || {
        for _ in 1..=5 {
            println!("hi {}!", name);
            thread::sleep(Duration::from_secs(1));
        }
    });
    handle.join().expect("unable to join thread");
}

Channels

rust supports message passing between threads using a FIFO queue.