简体   繁体   English

如何使用 Rust 创建死锁?

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

I would like to know how to create a deadlock.我想知道如何创建死锁。

I tried to create a program in Rust that has a deadlock.我试图在 Rust 中创建一个有死锁的程序。

How to create one?如何创建一个?

A very simple variant:一个非常简单的变体:

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
}

Same as in other programming languages, Rust can have silent killer deadlocks.与其他编程语言一样,Rust 可能会出现无声杀手死锁。

If some thread locking a mutex is waiting for another, this is not a good sign: if that other cannot come, the first mutex will never be released.如果某个锁定互斥体的线程正在等待另一个,这不是一个好兆头:如果另一个不能来,第一个互斥体将永远不会被释放。

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");
}

Which outputs哪些输出

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

and then waits forever然后永远等待

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM