dimanche 22 septembre 2019

Communicating with a GUI thread that is not the main thread

I managed to implement a GUI Qt-based application in a worker C++ std::thread like described here. Now I need both the main and worker threads to communicate.

My question is: how can I communicate messages (an array of floats) from my main thread to the worker thread so that I can update the GUI?

I tried using the Futures/Promises approach described here. Altough I was able to get this example running, I couldn't integrate into my project. The reason is that this approach relies on having a busy loop inside the worker thread that is constantly checking whether a new message has been sent by the main thread. However, in a Qt application, the program blocks once it enters the main event loop in a.exec(). This prevents the busy loop check and hence causing the program to deadlock.

This is how I am spawning the GUI worker thread (based on this post).

#include <thread>

// Start the Qt realtime plot demo in a worker thread
int argc = 0;
char **argv = NULL;
std::thread t1
        (
                [&] {
                    QApplication application(argc, argv);
                    MainWindow mainWindow;
                    mainWindow.show();
                    return application.exec();
                }
        );

Aucun commentaire:

Enregistrer un commentaire