rust 多线程

多线程之间的通信和内存共享常见方式

use std::sync::mpsc;
use std::thread;
use std::sync::{Arc,Mutex};

struct User {
    name: String
}

fn main() {

    // Arc 通过共享内存 在线程间通信  数据不可修改(所以这里使用的不可变引用)
    let usr_raw = Arc::new(User{ name: "Bob".to_string()});
    let usr = usr_raw.clone();
    let t1 = thread::spawn(move ||{
        println!("name :{}",&usr.name);
    });
    let usr = usr_raw.clone();
    let t2 = thread::spawn(move ||{
        println!("name :{}",&usr.name);
    });

    t1.join().unwrap();
    t2.join().unwrap();

    
    // 通过共享内存 在线程间通信  数据可修改,Mutex保证了数据可在线程间被安全的修改(一次只被一个线程修改)
    let raw = Arc::new(Mutex::new(0));
    let mut handle = vec![];
    for i in 0..5 {
        let raw = Arc::clone(&raw);
        let h = thread::spawn(move || {
            println!("thread :{}", i );
            *raw.lock().unwrap() += 1;
        });
        handle.push(h);
    }

    for i in handle {
        i.join().unwrap();
    }
    print!("{}",raw.lock().unwrap());


    // 通过通信 在线程间共享数据
    let (tx,rx) = mpsc::channel();
    let tx2 = mpsc::Sender::clone(&tx); //     let tx2 = tx.clone();
    thread::spawn(move || {
        let df = vec!["java","perl","python"];
        for i in df {
            println!("tx2 send {}",i);
            tx2.send(i).unwrap();
        }
    });

    thread::spawn(move || {
        let df = vec!["java","c","cpp","rust"];
        for i in df {
            println!("tx send {}",i);
            tx.send(i).unwrap();
        }
    });

    for ret in rx {
        println!("tx recv : {}", ret);
    }

}
posted @ 2023-09-09 19:54  天使不设防  阅读(39)  评论(0编辑  收藏  举报