Hey y'all.
I just had a problem with some multi-threaded code. I solved it myself but figured I would share it none the less since I couldn't find a solution online. I'm sure it exists somewhere.
use std::thread;
use ndarray::array;
fn main() {
let mut pool = vec![];
for i in 0..4 {
let handle = thread::spawn(move || {
let arr = array![0, 1, 2];
println!("{}", &arr[i]);
});
pool.push(handle);
}
pool.into_iter().for_each(|handle| handle.join().unwrap());
}
0
1
thread '<unnamed>' panicked at 'ndarray: index out of bounds', $HOME/.cargo/registry/src/github.com-1ecc6299db9ec823/ndarray-0.15.6/src/arraytraits.rs:27:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
2
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Any { .. }', src/bin/test.rs:14:54
Of course here it is obvious that the error is happening at the array access &arr[i]
because i
will go out of bounds.
But rust didn't show that line as the source of the error, but a line inside ndarray:
$HOME/.cargo/registry/src/github.com-1ecc6299db9ec823/ndarray-0.15.6/src/arraytraits.rs:27:5
.
I thought this had something to do with multi-threading but actually it's just because I ran it in release mode. Running it in debug produced the expected output.
0
1
2
thread '<unnamed>' panicked at 'ndarray: index 3 is out of bounds for array of shape [3]', src/bin/test.rs:10:29
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Any { .. }', src/bin/test.rs:14:54
So for anyone running into this issue and thinking it has something to do with multi-threading... It doesn't