プログラムのお勉強メモ

プログラムの勉強メモです. Python, Rust, など.

実践Rustプログラミング入門 4日目

4日目の勉強

  • 共有メモリ

共有メモリ

  • 複数のスレッド間で同じメモリ領域を共有する
  • 複数の所有者でメモリを共有するために RcArc というものがある
    • Rc は マルチスレッドに対応していない
    • Arc は マルチスレッド対応だが少しオーバヘッドが多い
  • Arc 単体だと排他制御に対応していないため, 共有メモリの変更が必要な場合Mutexで排他制御を行う必要がある

各スレッドから1つのベクターを読み込む

use std::sync::Arc;
use std::thread;

fn main() {
    let rc = Arc::new(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    let mut threads = vec![];

    for x in 0..10 {
        let c_rc = rc.clone();
        let t = thread::spawn(move || {
            println!("thead = {}, value = {}", x, c_rc[x]);
        });
        threads.push(t);
    }

    for t in threads {
        let _ = t.join();
    }
}

出力結果

thead = 0, value = 0
thead = 1, value = 1
thead = 2, value = 2
thead = 4, value = 4
thead = 3, value = 3
thead = 5, value = 5
thead = 8, value = 8
thead = 6, value = 6
thead = 9, value = 9
thead = 7, value = 7

各スレッドから1つのベクターに書き込む

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

fn main() {
    let mut handles = vec![];
    let data = Arc::new(Mutex::new(vec![0; 10]));

    for x in 0..10 {
        let data_ref = data.clone();
        handles.push(thread::spawn(move || {
            let mut data = data_ref.lock().unwrap();
            data[x] += 1;
        }))
    }

    for handle in handles {
        let _ = handle.join();
    }

    dbg!(data);
}

出力結果

[src\main.rs:20] data = Mutex {
    data: [
        1,
        1,
        1,
        1,
        1,
        1,
        1,
        1,
        1,
        1,
    ],

所感

  • 体調を崩して少し時間が空きました
  • 急に難しくなったなという印象
  • いまいち使いみちがわからない

多謝