首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向量(或向量向量)上的并发运算

向量(或向量向量)上的并发运算
EN

Stack Overflow用户
提问于 2021-09-07 19:00:23
回答 1查看 583关注 0票数 1

我将要编写一个Rust程序,在这里我想实现并发性。我的数据将存储在向量,或向量向量,无论我能使工作最容易。下面是一些伪代码,以显示如何设置结构和向量。显然语法是不正确的。

代码语言:javascript
复制
struct Artifact
    identifier = "abc123";
    vector_containing_Line_structs = [struct Line, struct Line, struct Line, ..., etc];
    // ^ this vector will contain thousands of line structs

struct Line
    line_type = 1
    speed = 5
    array_length = 4;
    array = {10, 20, 30, 40}

本质上,这就是我目前正在考虑如何存储我的数据(开放思想)。在以后的程序中,我想使用多线程并发地对vector_containing_Line_structs向量的子集执行计算。Thread1操作索引0-10000,thread2操作索引10001-20000等。线程是只读的,它们不会将任何东西写回Line,只访问每个线程中的数组和结构“变量”。

生锈编译器会让不同的线程并发地在同一向量内的项上操作吗?或者,我是否可以将这些数据分开,以便以一种保留订单/索引并允许以类似方式进行并发计算的方式来组织这些数据?

--我唯一的想法是向量。vector some_vector = [ [10k Line structs], [10k Line Structs], ... ]。我希望Rust能让我把每个子向量分配给不同的线程。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-07 22:16:58

由于您的问题不是特定于结构的成员,而是关于跨多个线程从共享向量读取数据的能力,这里有一个处理简单整数向量的简单示例。

引用或切片不能直接传递给线程,因为编译器不能证明引用的数据将比线程更长。然后,我们使用一个Arc,只要线程存在,就可以保持这些数据的存活。

从线程中获得一些部分结果通常是用频道完成的。

文档

代码语言:javascript
复制
fn main() {
    // prepare vector to be shared
    let mut data = Vec::new();
    for i in 0..10_000 {
        data.push(i);
    }
    // make it accessible to multiple threads
    let data = std::sync::Arc::new(data);
    // prepare communication channel
    let (tx, rx) = std::sync::mpsc::channel();
    // launch the desired number of threads
    let thread_count = 8;
    let mut threads = Vec::new();
    for idx in 0..thread_count {
        // clone shared ressources in order to move them into the thread
        let tx = tx.clone();
        let data = data.clone();
        threads.push(std::thread::spawn(move || {
            // determine the part of shared data to be accessed by this thread
            let begin = data.len() * idx / thread_count;
            let end = data.len() * (idx + 1) / thread_count;
            let slc = &data[begin..end];
            // work on this slice
            let mut sum = 0;
            for v in slc {
                sum += v;
            }
            println!("thread {} --> {}", idx, sum);
            // send a result to main thread
            tx.send(sum).unwrap();
        }));
    }
    // wait for threads and collect results
    let mut result = 0;
    for th in threads {
        result += rx.recv().unwrap();
        th.join().unwrap();
    }
    println!("done: {}", result);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69093351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档