Tokio -- unable to loop indefinitely

I am writing a program in Tokio that performs both synchronous and async tasks. This is my main function:

#[tokio::main]
async fn main() {
    let mut image = image::load(BufReader::new(File::open(IMAGE_DIR).unwrap()), image::ImageFormat::Png).unwrap();
    let height = image.height();
    let width = image.width();
    let done = false;

    loop {
        let image_vec = image_to_vec(image.as_rgba8().unwrap().to_owned());
        let mut threads = Vec::<tokio::task::JoinHandle<(Vec<[u8; 4]>, bool)>>::new();

        for j in 0..width {
            let row = image_vec[j as usize].clone();
            threads.push(tokio::spawn(async move {
                bubble_sort_row(&row, j as usize, height as usize).await
            }));
        }

        let results = futures::future::join_all(threads).await;

        let image_vec = results.iter()
                               .map(|v| {
                                   v.as_ref().unwrap().clone().0
                               })
                               .collect::<Vec<Vec<[u8; 4]>>>();

        image = vec_to_image(image_vec).into();
        image.save(format!("{OUTPUT_DIR}/0.png")).unwrap();
    }
}

The expected behavior is for the program to continue indefinitely, performing bubble sort on the image saved in the last iteration of the loop. However, the program only does one iteration before exiting. I assume this is related to the async parts, but I'm not sure how to fix it.

Any help is appreciated

I'm guessing that one of the unwrap calls is causing the program to panic, which will print a backtrace and exit. What output do you see when you run the program in the terminal?

Turns out my infinite debugging messages were hiding an error... I get index out of bounds: the len is 3115 but the index is 3115 on the line with let row = image_vec[j as usize].clone();.

1 Like

It was because one of my (un)helper functions rotated the image 90 degrees for an unknown reason, causing the width value (which was defined outside of the loop) to change. I'm still debugging, but at least I have an idea what's going on now :stuck_out_tongue:

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.