簡體   English   中英

如何使用 Rust 創建死鎖?

[英]How can I create a deadlock with Rust?

我想知道如何創建死鎖。

我試圖在 Rust 中創建一個有死鎖的程序。

如何創建一個?

一個非常簡單的變體:

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

fn main() {
    let data = Arc::new(Mutex::new(0));
    let d1 = data.lock();
    let d2 = data.lock(); // cannot lock, since d1 is still active
}

與其他編程語言一樣,Rust 可能會出現無聲殺手死鎖。

如果某個鎖定互斥體的線程正在等待另一個,這不是一個好兆頭:如果另一個不能來,第一個互斥體將永遠不會被釋放。

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

use lazy_static::lazy_static;
lazy_static! {
    static ref MUTEX1: Mutex<i64> = Mutex::new(0);
    static ref MUTEX2: Mutex<i64> = Mutex::new(0);
}

fn main() {
    // Spawn thread and store handles
    let mut children = vec![];
    for i_thread in 0..2 {
        children.push(thread::spawn(move || {
            for _ in 0..1 {
                // Thread 1
                if i_thread % 2 == 0 {
                    // Lock mutex1
                    // No need to specify type but yes create a dummy variable to prevent rust
                    // compiler from being lazy
                    let _guard: MutexGuard<i64> = MUTEX1.lock().unwrap();

                    // Just log
                    println!("Thread {} locked mutex1 and will try to lock the mutex2, after a nap !", i_thread);

                    // Here I sleep to let Thread 2 lock mutex2
                    sleep(Duration::from_millis(10));

                    // Lock mutex 2
                    let _guard = MUTEX2.lock().unwrap();
                // Thread 2
                } else {
                    // Lock mutex 1
                    let _guard = MUTEX2.lock().unwrap();

                    println!("Thread {} locked mutex2 and will try to lock the mutex1", i_thread);

                    // Here I freeze !
                    let _guard = MUTEX1.lock().unwrap();
                }
            }
        }));
    }

    // Wait
    for child in children {
        let _ = child.join();
    }

    println!("This is not printed");
}

哪些輸出

Thread 0 locked mutex1 and will try to lock the mutex2, after a nap !
Thread 1 locked mutex2 and will try to lock the mutex1

然后永遠等待

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM