1

I'm struggeling to get my multi-threaded matrix multiplication compiling. I want to transfer the naive algorithm in a way that one thread calculates one cell of the result matrix.

My code looks like this:

pub fn multiply_fast(mat1: &Matrix, mat2: &Matrix) -> Matrix {
    let result_mat = Matrix::new(mat1.height, mat2.width);

    let mut handles = Vec::new();

    // for each row of Matrix A
    for i in 0..result_mat.height {
        // for each col of Matrix B
        for j in 0..result_mat.width {

            let handle = thread::spawn(|| {
                let mut c = 0_f64;
                // foreach row of A / col of B
                for z in 0..mat1.width {
                    c += mat1.data[i * mat1.width + z] * mat2.data[z * mat2.width + j]
                }
                result_mat.data[i * result_mat.width + j] = c;
            });
            handles.push(handle);
        }
    }

    for x in handles {
        x.join().unwrap();
    }
    result_mat
}

Rust Compiler tells me that mat1 and mat2 should have static lifetime. I think I get around this if I create data slices with just the values that one thread needs. Then I move them into the closure.

I have a good basic understanding of all the aspects of Rust I think. But I can't get this work even after trying a lot. Can someone please provide me some code?

phip1611
  • 5,460
  • 4
  • 30
  • 57
  • Well I think I got it. I create two new vars per iteration and one is representing the col of matrix 2 and one the row of matrix 1. I transfer the ownership to the thread. But even if I do it like this I can't make the whole thing work.. – phip1611 Aug 20 '19 at 14:07
  • 4
    Feel free to experiment, but my gut tells me that spawning one thread per cell is going to be terribly inefficient. – Shepmaster Aug 20 '19 at 14:09
  • An alternative could be to use rayon that has a thread pool, but I'm not even sure that it would be more efficient. – Boiethios Aug 20 '19 at 14:12

0 Answers0