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.

Anon
  • 3,565
  • 3
  • 27
  • 45
  • 1
    Does this answer your question? [The meaning of asynchronous vs synchronous](https://softwareengineering.stackexchange.com/questions/396585/the-meaning-of-asynchronous-vs-synchronous) – Ben Cottrell Jul 22 '22 at 07: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? – Kevin Krumwiede Jul 23 '22 at 04: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. – Anon Jul 23 '22 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? – Kevin Krumwiede Aug 01 '22 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::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();` – Anon Aug 02 '22 at 06:25

0 Answers0