c++ – Concurrent dependant routines in a gui application


The idea is that, in my application I have 5 routines named long_process_1, long_process_2, long_process_3, long_process_4, long_process_5. These are each long calculations that would hang the GUI and can only be called in that order. When each result is ready, user input is required about the result. So we call ask_user_1, ask_user_2, ask_user_3, ask_user_4, ask_user_5 which must obviously run in the main GUI thread. Thus the whole thing cannot be run in a separate thread in its entirety. Here’s how I did it:

void MainWindow::on_button_click() // starts with a button click
{
    QEventLoop eventLoop;
    QFutureWatcher<int> watch;

    // Watcher intercepts eventLoop when the computation is finished
    connect(&watch, &decltype(watch)::finished, &eventLoop, &decltype(eventLoop)::quit);

    auto const res1 = QtConcurrent::run(long_process_1);
    watch.setFuture(res1);
    eventLoop.exec(); // Handles GUI during computation
    auto const user_in1 = ask_user_1(res1);

    auto const res2 = QtConcurrent::run(long_process_2, user_in1);
    watch.setFuture(res2);
    eventLoop.exec();
    auto const user_in2 = ask_user_2(res2);

    auto const res3 = QtConcurrent::run(long_process_3, user_in2);
    watch.setFuture(res3);
    eventLoop.exec();
    auto const user_in3 = ask_user_3(res3);

    auto const res4 = QtConcurrent::run(long_process_4, user_in3);
    watch.setFuture(res4);
    eventLoop.exec();
    auto const user_in4 = ask_user_4(res4);

    auto res5 = QtConcurrent::run(long_process_5, user_in4);
    watch.setFuture(res5);
    eventLoop.exec();
    (void)ask_user_5(res5); // result is not used
}

This works alright. I find this a lot simpler than running the whole thing through “on-finished” signal-slots. It also simplifies ownership of local variables/function results as they are all in a single function. The long routines are clearly decoupled from the function calling them. It seems a bit odd overall though. I got the idea from very old Qt docs. All comments are welcome.