1

Backstory

Probably a stupid question, but I just have a sneaking suspicion that "asynchronous" is the wrong terminology to us for naming my template function here:

template <class T>
auto asynchronous( auto &&lambda )
{
    QEventLoop wait;
    QFutureWatcher<T> fw;
    fw.setFuture( QtConcurrent::run(lambda) );
    QObject::connect( &fw, &QFutureWatcher<T>::finished, &wait, &QEventLoop::quit );
    wait.exec();
    QObject::disconnect( &fw, &QFutureWatcher<T>::finished, &wait, &QEventLoop::quit );
    return fw.result();
}

in practice it looks like this:

int n(0);
ct_Start(n); // 0 - Running in main thread
n = asynchronous<int>( [&n](){
    // Running in background thread.
    // Mainthread is waiting for this lambda to finish
    // but mainthread is not locked. 
    // User Interface will still function.
    for ( int i = 0; i < 100000; i++ ){
        ct_Debug(n++); 
    };
    return n;
});
ct_Finish(n); // 100000

Question

So generally when you place a function on a seperate thread, allowing the main thread to continue, it is usually called asynchronous. However, while I am not blocking my main thread, it is still waiting for the lambda to finish.

  1. Is naming this function "asynchronous" misleading?
  2. Is this example considered synchronous, asynchronous, both, or neither?
  3. Is there better more specific terminology that could be used instead?

Thanks.

5
  • 1
    Does this answer your question? The meaning of asynchronous vs synchronous Commented Jul 22, 2022 at 7:04
  • If the main thread is waiting for the other thread to finish, why not just have the main thread do what the other thread is doing? Commented Jul 23, 2022 at 4:02
  • 2
    @KevinKrumwiede The mainthread in Qt is responsible for running the GUI. If you put a resource intensive task on the mainthread, it locks up the GUI. Its not a good thing to do. Commented Jul 23, 2022 at 22:50
  • @Anon Yes, that's how most (all?) UI toolkits work. The code comment says this code doesn't block, but is that true? Commented Aug 1, 2022 at 21:02
  • @KevinKrumwiede [ Assuming I am understanding your question properly ] There are two ways to wait in a thread: 1) Blocking the thread, waiting for a mutex to unlock. 2) Returning control to the main event loop, which listens for calls to dispatch [ Such as GUI functionality ]. My example does the latter, note: QEventLoop wait; & Object::connect( &fw, &QFutureWatcher<T>::finished, &wait, &QEventLoop::quit ); -- finished is a signal that calls quit() on the local eventloop wait. After that, the main eventloop dispatches control to the code following wait.exec(); Commented Aug 2, 2022 at 6:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.