Architecture for Qt application with Lua scripting - pause execution - c++

My embedded project contains a Qt application for the PC which is mainly a simulator for debugging and testing. In the application I can create several widgets which represent either my embedded software or simulate the hardware controlled by the application or can generate external inputs for testing.
I plan to improve the application by adding Lua scripting so that the widgets can be created or controlled from a script. I need an elegant way for single stepping the scripts.
I plan scripts like:
createThermometerWidget(10,20,30)
while time < maxTime do
setTemperature(20+time/1000)
pauseSimulation()
time = time + 1
end
The custom function pauseSimulation should stop the Lua script, enable the Qt event loop to run so that interaction with the software is possible (seting other inputs for example) and after pressing a button the script will continue.
My first idea was to create a separate thread for the Lua execution which will be stopped by pauseSimulation and released by the button. But Qt widgets cannot be created from non-main thread so that I will have to create all widgets in the main thread and pass all constructor parameters from Lua functions to the main thread.
Is there a more smooth way?

Coroutines are one approach to implementing this. Your pauseSimulation() can internally call coroutine.yield(), and be restarted later by a call to coroutine.resume() from the button's action. The problem is that your UI is at the mercy of your script fragments, since the only way to halt a running coroutine is for it to eventally call yield().
Alternatively, you can use the Lanes module to put part of your Lua application into a separate thread. You would use a Linda to pass messages from the main Qt widget thread to your simulator's worker thread. This would have the advantage that the UI thread is not blocked by the simulation which runs in its own thread.

Related

Qt undo/redo and threads

In my MDI application I use the Qt undo/redo framework and it works very well.
Now I have implemented an operation that requires a lot of time, so I would like to run it in another thread so that the application is not freezed and the user can work on the other MDI windows meanwhile.
So I have to run the operation in a new thread inside the redo() method of my QUndoCommand. This is a problem, because:
If I wait inside the redo() method that the thread has finished, the application freezes, so it is useless.
If I don't wait that thread has finished, the redo() method returns before the operation is completed, and this can cause a lot of problems and errors (e.g. if the user uses the undo/redo mechanism, it is possible that the commands following the thread command are executed before it is completed).
Any idea?
You have much bigger problems than undo/redo. Change the architecture so that system behavior is sane when asynchronous data processing is underway. The data manager object should indicate when it's busy, and the UI should reflect that. Once you get this working properly, undo/redo will magically work as well.

How to execute in C++ a task in the Windows main loop

Is there a way to schedule a task to be executed in the Windows main loop. I don't want to create a Windows and send an event to it.
With libdispatch I can do it with:
dispatch_async_f(dispatch_get_main_queue(), ...)
Or is there a thread in the Windows Thread Pool associated with the program's main loop?
Background:
Currently I am in the process of developing a CSP (Communicating Sequential Processing) library and most of the time tasks can be executed by the Thread Pool. But sometimes there is the need that a task is executed in the main loop. I have already a solution, if the application under Windows is a Qt application. But for non Qt applications under Windows I would like to have a solution as well.
On Windows each message loop is associated with a single thread. You can have more than one message loop per application if this is what you ask.

What is the trick to run a member function in the back-end without slowing down the main application?

Sorry I don't know how to phrase this in the title, maybe someone could help me.
I am starting to make a Qt application, let's say, the application will first show N points on the screen. Then we have a function now, called movePoints, when it is called, these points will be moved according to some algorithms.
Now when N is small, everything looks very smooth, it works very well without any problem. But if N is very large, the whole GUI sucks because movePoints is running. So whenever I touch the application window now, it becomes unresponding. But I know lots of programs seem to be able to let the movePoints function run in the back-end (with a progress bar in the status bar or something) without slowing down the main application. How can I achieve this effect?
To keep your application responsive to user interactions, you should use the processEvents function. (http://qt-project.org/doc/qt-4.8/qcoreapplication.html#processEvents)
If you'd rather have the operation occur in the background you can use the QtConcurrent module and use the asynchronous run function (http://qt-project.org/doc/qt-4.8/qtconcurrentrun.html).
Use a QTimer for an interrupt or a QThread to bring the calculation out of the main loop. See: http://qt-project.org/doc/qt-4.8/threads.html
You can use a separate thread to perform calculations in the background without blocking the Qt event loop. See QThread and QConcurrent. It's common practice in processing-intensive Qt applications to have the main thread handle the GUI while "back-end" calculations are done in "worker" threads.
If rendering the data (rather than just calculating the next state) is also an intensive operation, you can also use your worker thread(s) to create a QImage, QGraphicsScene, or similar type of object, and send it pre-built to the UI thread.
If you're limited to a single thread (e.g. your platform doesn't really support threads), then you can take your algorithm and intersperse calls to QCoreApplication::proccessEvents, which will make the GUI more responsive while the activity runs. I find that using actual threads tends to be the simpler and more maintainable approach, though.

Best way to multithread UI?

As stated clearly in the documentation, Qt GUI must be accessed from main thread only. For complex app with multiple large and busy tables, this can be a bottleneck just from all the font-size text metrics calculations Qt likes to do. The only alternative I can think of is multi-tasking with separate processes. The tables are currently about as fast as you can get, custom model that is direct-mapped to a cache that is fed from another thread using dataChanged() calls on the most conservative set of changed cells. I've already profiled with vTune, 70% of the app time is now in Qt rendering code. Any suggestions?
I havn't used QT, but accessing GUI from only one thread (the GUI thread) is a known matter in almost any GUI I'm familiar with. I used 2 solutions for this case, of which I prefer the first one:
1) Your form will update the GUI (table, in this case) at timer intervals. The timer is activated on the GUI thread's events. At those timer events you read the data from global vars and update your table. The global vars can be updated by as many threads as you wish. You might need to synch (semaphores, for examples) the access to the global vars.
2) In many GUI APIs threads can update the GUI by handing the GUI thread a function (or an object) and ask it to execute it ASAP on its context. The calling thread meanwhile blocks, until the GUI fulfilled the action. I can recall three such functions - Invoke, InvokeLater from Java and C#, or wx.CallAfter of wxPython.
Use a variant of MVC pattern and make the model multithread
If your table entries and methods are done in several steps, you can call QCoreApplication::processEvents() to update the qt ui in between the calculations. Another thing you can do is run everything on different thread and emit signals from the thread when the calculations are complete. At the end, the updates are done on the ui from the main thread but asynchronously. To connect to a signal from a different thread you'll have to use qRegisterMetaType<>.

Qt Events after a long routine freezes my application for a while

So, I have a single-threaded application which loads data from a set of file:
QStringList qFiles = QFileDialog::getOpenFileNames(
this,
"Choose Image Files",
"",
"Dicom Files(*.dcm);;All Files(*)"
);
After that I invoke a library which will parse the set of files, since the library invokes OpenGL functions I may not create a new thread for this processing.
Once this processing is done I noticed my application froze for a while.
Using GDB I noticed my Qt Application buffered a lot of Events while the library processed the set of files and then it is processing these events.
I may not invoke QApplication::instance()->processEvents() inside the libary, because it doesnt know Qt(project decision).
Is there way to discard these events? Or is there any other solution to keep my application from freezing?
Move OpenGL Rendering to a Worker Thread
If possible, move your OpenGL rendering to a separate thread. Then you can call your library functions there and not worry about them blocking the event queue.
You should be able to devote your framebuffer to the worker thread and communicate with it using signals and slots just fine.
Alternative: Implement Progress Callbacks
Alternatively you could see if the library has any callbacks. If you have source available, you could implement your own during long-running operations.