Help with multithreading - x/y axis manipulation

Hello,

I am trying to implement simple stepper motors controller where two mottors will be responsible for moving intro two directions independently. Here is the idea:

Given following code:

struct Move {
    x_dir: i32,
    y_dir: i32,
    draw: bool
}

let moves = vec![
        Move { x_dir: 32, y_dir: 10, draw: false },
        Move { x_dir: 2, y_dir: 20, draw: true },
        Move { x_dir: 12, y_dir: 43, draw: true },
        Move { x_dir: 43, y_dir: 23, draw: false }
];

I would like to spawn two threads, first for motor controlling x axis and second for controlling y axis. Then I would like to iterate over 'moves' array, and for each 'move' execute code moving each motor on separate threads. And when they are done proceed with next 'move' element. I have just read about mutexes (they seem to fit here) but I cant figure out how to properly implement that in rust. Can you please help me with some basic example or at least general idea of doing that? Regards

As your data comes in x/y pairs, you definitely do not want to split that up.
It should be absolutely no problem to run many motors in a single thread.

Please format your code according to the new-user instructions for this forum. You can edit your initial post by clicking on the edit button under that post.

Yes, I agree that it may not be the best idea, but just as a practice. I have implemented following snippet using tokio:

    let moves = vec![
        Move { x_dir: 32, y_dir: 10, draw: false },
        Move { x_dir: 2, y_dir: 20, draw: true },
        Move { x_dir: 12, y_dir: 43, draw: true },
        Move { x_dir: 43, y_dir: 23, draw: false }
    ];

    for each_move in moves {
        println!("Next move!");
        let join = task::spawn(async move {
            let ten_millis = time::Duration::from_secs(5);
            sleep(ten_millis);
            println!("Moved : X axis {}", each_move.x_dir);
        });

        let join1 = task::spawn(async move {
            let ten_millis = time::Duration::from_secs(10);
            sleep(ten_millis);
            println!("Moved : Y axis {}", each_move.y_dir);
        });
        tokio::join!(join, join1);
    }

Is it a proper way to do that?

No need for async here. just some plain old std::thread::spawn and std::thread::sleep.

Why is it better here?

I assumed you wanted OS threads, not tasks (multiple tasks per thread).

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.