线程不并行运行

时间:2015-05-26 16:05:29

标签: multithreading rust

我正在尝试按照官方文档来掌握语言的意义。但是,我遇到的问题是线程没有在this tutorial中并行运行。

我试图通过在代码中引入一些更改来使问题更加明显,但一切都没有改变。这是来源:

src/main.rs

extern crate rand;

use rand::Rng;
use std::sync::{Arc, Mutex};
use std::thread;

struct Philosopher {
    name: String,
    left: usize,
    right: usize,
}

struct Table {
    forks: Vec<Mutex<()>>,
}

impl Philosopher {
    fn new(name: &str, left: usize, right: usize) -> Philosopher {
        Philosopher {
            name: name.to_string(),
            left: left,
            right: right,
        }
    }

    fn eat(&self, table: &Table) {
        let _left = table.forks[self.left].lock().unwrap();
        let _right = table.forks[self.right].lock().unwrap();
        let sleeptime = rand::thread_rng().gen_range(1, 1001);

        println!("{} is eating for {} milliseconds.", self.name, sleeptime);
        thread::sleep_ms(sleeptime);
        println!("{} is done eating.", self.name);
    }
}

fn main() {
    let table = Arc::new(Table {
        forks: vec![
            Mutex::new(()),
            Mutex::new(()),
            Mutex::new(()),
            Mutex::new(()),
            Mutex::new(()),
        ],
    });
    let philosophers = vec![
        Philosopher::new("Baruch Spinoza", 0, 1),
        Philosopher::new("Gilles Deleuze", 1, 2),
        Philosopher::new("Karl Marx", 2, 3),
        Philosopher::new("Friedrich Nietzsche", 3, 4),
        Philosopher::new("Michel Foucault", 0, 4),
    ];

    let handles: Vec<_> = philosophers.into_iter().map(|p| {
        let table = table.clone();
        thread::spawn(move || p.eat(&table))
    }).collect();

    for h in handles {
        h.join().unwrap();
    }
}

Cargo.toml

[package]
name = "philosophers"
version = "0.1.0"
authors = ["shinkou <someone@somewhere.com>"]

[dependencies]
rand = "0.3.0"

我不确定我的设置是否是原因,但我在Win7下的VM(Ubuntu 14.10)上测试它。

我运行了很多代码(20多次)。没有一个例外,订单总是

Michel Foucault is eating for 214 milliseconds.
Michel Foucault is done eating.
Friedrich Nietzsche is eating for 34 milliseconds.
Friedrich Nietzsche is done eating.
Karl Marx is eating for 167 milliseconds.
Karl Marx is done eating.
Gilles Deleuze is eating for 813 milliseconds.
Gilles Deleuze is done eating.
Baruch Spinoza is eating for 207 milliseconds.
Baruch Spinoza is done eating.

然而,当我回到家中并在我的Slackware64(14.1)框中运行它时,订单会随机变化。

编辑:添加代码以打印出随机进食时间

0 个答案:

没有答案
相关问题