Rust:为什么带有Vec >的指针在多线程中无法正常写入数据?

问题描述 投票:-1回答:1

Rust:为什么使用Vec的指针>在多线程中无法正常写入数据?

我想在多线程并行中修改big vec。

工作正常:u32

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

fn main() {
    let input = Arc::new([1u32, 2, 3, 4]);

    let mut handles = Vec::new();

    for t in 0..4 {
        let inp = input.clone();
        let handle = thread::spawn(move || unsafe {
            let p = (inp.as_ptr() as *mut u32).offset(t as isize);
            *p = inp[t] + t as u32 ;
        });

        handles.push(handle);
    }

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

    println!("{:?}", input);
}

效果不佳:Vec>

当我将u32更改为Vec时,指针工作不正常。

use std::thread;
use std::sync::Arc;
use std::collections::HashSet;

fn main() {

    let mut a = HashSet::new();
    a.insert("aaa");
    let input = Arc::new(vec![a.clone(), a.clone(), a.clone(), a.clone()]);

    let mut handles = Vec::new();

    for _t in 0..4 {
        let inp = input.clone();
        let handle = thread::spawn(move || unsafe {
            let p = (inp.as_ptr() as *mut Vec<HashSet<&str>>).offset(0);
            (*p)[0].insert("bbb");
        });

        handles.push(handle);
    }

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

    println!("{:?}", input);
}

Rust:为什么使用Vec的指针>在多线程中无法正常写入数据?

multithreading pointers rust automatic-ref-counting
1个回答
0
投票

我找到了方法:

use std::thread;
use std::sync::Arc;
use std::collections::HashSet;

fn main() {
    let mut a = HashSet::new();
    a.insert("aaa");
    let input = Arc::new(vec![a.clone(), a.clone(), a.clone(), a.clone()]);

    let mut handles = Vec::new();

    for _t in 0..4 {
        let inp = input.clone();
        //let out = output.clone();
        let handle = thread::spawn(move || unsafe {
            let p = (inp.as_ptr() as *mut Vec<HashSet<&str>>).offset(0);

            (*p)[0].insert("bbb");
        });

        handles.push(handle);
    }


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

    println!("{:?}", input);
}

谢谢大家!

© www.soinside.com 2019 - 2024. All rights reserved.