Rust 死锁例子。

一个简单的rust死锁例子。

use std::sync::{Arc, Mutex};
use std::{thread, time::Duration};

fn main() {
    let lock1 = Arc::new(Mutex::new(1));
    let lock2 = Arc::new(Mutex::new(2));

    let lock1a1 = Arc::clone(&lock1);
    let lock2a1 = Arc::clone(&lock2);
    let handel1 = thread::spawn(move || {
        println!("handel1 开始获取 lock1");
        let mut _a1 = lock1a1.lock().unwrap();
        println!("handel1 已获取 lock1 并使用");
        thread::sleep(Duration::from_secs(1));
        println!("handel1 开始获取 lock2");
        let _a2 = lock2a1.lock().unwrap();
        println!("handel1 已获取 lock1 和 lock2");
    });

    let lock1a2 = Arc::clone(&lock1);
    let lock2a2 = Arc::clone(&lock2);
    let handel2 = thread::spawn(move || {
        println!("handel2 开始获取 lock2");
        let mut _a2 = lock2a2.lock().unwrap();
        println!("handel2 已获取 lock2 并使用");
        thread::sleep(Duration::from_secs(1));
        println!("handel2 开始获取 lock1");
        let _a1 = lock1a2.lock().unwrap();
        println!("handel2 已获取 lock1 和 lock2");
    });

    handel1.join().unwrap();
    handel2.join().unwrap();
    println!("未发生死锁!");
}

//消息传递
fn lock_message_passing() {
    let (tx1, rx1) = mpsc::channel();
    let (tx2, rx2) = mpsc::channel();

    thread::spawn(move || {
        println!("rx1接收消息");
        rx1.recv().unwrap();

        println!("tx2发送消息");
        tx2.send("t").unwrap();
    });

    println!("rx2接收消息");
    rx2.recv().unwrap();

    println!("tx1发送消息");
    tx1.send("t").unwrap();
}

 

posted @ 2022-02-14 16:08  贤云曳贺  阅读(422)  评论(0编辑  收藏  举报