代码之家  ›  专栏  ›  技术社区  ›  Bojangles Vincent Baillet

在线程之间发送Nalgebra向量

  •  3
  • Bojangles Vincent Baillet  · 技术社区  · 6 年前

    我在用Nalgebra的 VectorN<f64, N> 输入一些运行良好的单线程代码。我现在正在尝试多线程算法的各个部分,但是遇到了传递 VectorN 变成一个 thread::spawn 打电话来。例如,以下代码无法编译:

    use std::thread;
    use nalgebra::{VectorN, DefaultAllocator, DimName};
    use nalgebra::allocator::Allocator;
    
    struct Test<N>
    where
        N: DimName,
        DefaultAllocator: Allocator<f64, N>,
    {
        pub field: VectorN<f64, N>,
    }
    
    impl<N> Test<N>
    where
        N: DimName,
        DefaultAllocator: Allocator<f64, N>,
    {
        pub fn test(&self) {
            let handle = thread::spawn(move || {
                let thing = self.field;
    
                let thing2 = thing * 2.0;
    
                thing2
            });
    
            let res = handle.join().unwrap();
        }
    }
    

    出现此错误时:

    error[E0277]: `<nalgebra::base::default_allocator::DefaultAllocator as nalgebra::base::allocator::Allocator<f64, N>>::Buffer` cannot be sent between threads safely
      --> trajectories/src/path/mod.rs:34:22
       |
    34 |         let handle = thread::spawn(move || {
       |                      ^^^^^^^^^^^^^ `<nalgebra::base::default_allocator::DefaultAllocator as nalgebra::base::allocator::Allocator<f64, N>>::Buffer` cannot be sent between threads safely
       |
       = help: within `nalgebra::base::matrix::Matrix<f64, N, nalgebra::base::dimension::U1, <nalgebra::base::default_allocator::DefaultAllocator as nalgebra::base::allocator::Allocator<f64, N>>::Buffer>`, the trait `std::marker::Send` is not
    implemented for `<nalgebra::base::default_allocator::DefaultAllocator as nalgebra::base::allocator::Allocator<f64, N>>::Buffer`
       = note: required because it appears within the type `nalgebra::base::matrix::Matrix<f64, N, nalgebra::base::dimension::U1, <nalgebra::base::default_allocator::DefaultAllocator as nalgebra::base::allocator::Allocator<f64, N>>::Buffer>`
       = note: required by `std::thread::spawn`
    

    我试过各种各样的定义 N DefaultAllocator where 条款,但还没走远。各种各样的搜索引擎在这个问题上没有发现任何有用的东西。

    如果我换了 矢量<f64,N> 具有 VectorN<f64, U3> (或任何其他 U* 从Nalgebra输入),上述错误消失。我读过 Nalgebra generic programming guide 不过,这似乎已经过时了,也许不是我需要的;我不想 完成 通用性,就是使用 矢量 任何尺寸的装订。我需要在我的结构上设置什么特征边界才能通过 field 变成一条线?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bojangles Vincent Baillet    6 年前

    我在黑暗中尝试了一下(基于编译器给出的错误消息),并通过添加 Allocator::Buffer 这样地:

    use nalgebra::allocator::Allocator;
    
    struct Test<N>
    where
        N: DimName,
        DefaultAllocator: Allocator<f64, N>,
        <DefaultAllocator as Allocator<f64, N>>::Buffer: Send + Sync,
    {
        pub field: VectorN<f64, N>,
    }
    
    // snip ...
    

    我不确定这是否是正确的方法,而且肯定会增加一些噪音,但现在似乎让我将Nalgebra构造传递到线程中。