2016-03-20 11 views
0

私は錆に慣れています。私は借りるというコンセプトに苦しんでいます。複数のスレッドに読み込み専用の行列(Vec <Vec<f64>>)を渡す

Vec<Vec<f64>>行列をロードして、それを並列処理したいとします。しかし、このコードをコンパイルしようとするとerror: capture of moved value: `matrix` [E0382]let _ =行になります。

この行列はスレッドのためだけに読み込まれるはずですが、変更されません。どのように私はそれを読み取り専用で渡すことができ、 "移動された値"のエラーをなくすことができますか?

fn process(matrix: &Vec<Vec<f64>>) { 
    // do nothing for now 
} 

fn test() { 
    let filename = "matrix.tsv"; 
    // loads matrix into a Vec<Vec<f64>> 
    let mut matrix = load_matrix(filename); 

    // Determine number of cpus 
    let ncpus = num_cpus::get(); 
    println!("Number of cpus on this machine: {}", ncpus); 
    for i in 0..ncpus { 
     // In the next line the "error: capture of moved value: matrix" happens 
     let _ = thread::spawn(move || { 
      println!("Thread number: {}", i); 
      process(&matrix); 
     }); 
    } 
    let d = Duration::from_millis(1000 * 1000); 
    thread::sleep(d); 
} 
+1

スライス/ベクトルの処理を複数のスレッドに分割することについて**多くの**質問があります。私は[this one](http://stackoverflow.com/q/28599334/155423)、[this one](http://stackoverflow.com/q/33818141/155423)、[this one](http: //stackoverflow.com/q/31644152/155423)。 – Shepmaster

答えて

3

(ポインタ)をカウントアトミック参照を表しArcに共有されるオブジェクトをラップ。各スレッドについて、このポインタを複製し、クローンの所有権をスレッドに渡します。ラップされたオブジェクトは、何も使用されなくなると割り当てが解除されます。

fn process(matrix: &Vec<Vec<f64>>) { 
    // do nothing for now 
} 

fn test() { 
    use std::sync::Arc; 
    let filename = "matrix.tsv"; 
    // loads matrix into a Vec<Vec<f64>> 
    let mut matrix = Arc::new(load_matrix(filename)); 

    // Determine number of cpus 
    let ncpus = num_cpus::get(); 
    println!("Number of cpus on this machine: {}", ncpus); 
    for i in 0..ncpus { 
     let matrix = matrix.clone(); 
     let _ = thread::spawn(move || { 
      println!("Thread number: {}", i); 
      process(&matrix); 
     }); 
    } 
    let d = Duration::from_millis(1000 * 1000); 
    thread::sleep(d); 
} 
+0

おかげで素晴らしい作品!。あなたは何をしているのか分かりませんが、私はそれを見て学習するつもりです;) – Mandragor

関連する問題