Function understand_shared_thread

Source
pub fn understand_shared_thread()
Expand description

§线程间共享数据

https://doc.rust-lang.org/std/time/struct.Duration.html

use std::thread;

fn main() {
    let mut v = vec![1,2,3];
    thread::spawn(move || {
        v.push(4);
    });
    // Can no longer access `v` here.
}
// invalid
use std::thread;

fn main() {
    let mut v = vec![1,2,3];
    for i in 0..10 {
        thread::spawn(move || {
            v.push(i);
        });
    }
}

借用检查阻止并发Bug

// invalid
fn inner_func(vref: &mut Vec<u32>) {
    std::thread::spawn(move || {
    vref.push(3);
    });
}

fn main() {
    let mut v = vec![1,2,3];
    inner_func(&mut v);
}

`‘static’ 与 线程安全

Note: 曾经的 thread::scoped 会泄漏 JoinGuard 所以被废弃

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

struct Foo {
    string: String,
    v: Vec<f64>,
}

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {:?}", self.string, self.v)
    }
}

fn test<T: Send + Sync + fmt::Display + 'static >(val: T) {
    thread::spawn(move || println!("{}", val));
}

fn main() {
    test("hello");                // &'static str
    test(String::from("hello"));  // String
    test(5);                      // i32

    // Arbitrary struct containing String and Vec<f64>
    test(Foo {string: String::from("hi"), v: vec![1.2, 2.3]});
    thread::sleep(Duration::new(1, 0));
}

使用 crossbeam::scope 共享数据

use crossbeam;
use std::{thread, time::Duration};

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];

    crossbeam::scope(|scope| {
        for e in &vec {
            scope.spawn(move |_| {
                println!("{:?}", e);
            });
        }
    })
    .expect("A child thread panicked");

    println!("{:?}", vec);
}

scope thread 修改数据

use crossbeam; // 0.6.0
use std::{thread, time::Duration};

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];

    crossbeam::scope(|scope| {
        for e in &mut vec {
            scope.spawn(move |_| {
                thread::sleep(Duration::from_secs(1));
                *e += 1;
            });
        }
    })
    .expect("A child thread panicked");

    println!("{:?}", vec);
}