I have a question concerning long calculations:
While executing some tasks of my GUI long calculations might be done. This is not a problem, it just takes a while – everything works fine (at least the results are fine).
What bothers me is that after a certain time my GUI doesn't seem to respond: For example my ProcessBar that is shown during calculations will not be displayed and in the title bar of my GUI the text “keine Rückmeldung” is added (which means something like busy, crashed, etc - sorry I don't know the correct translation which makes it hard for me to find anything in the internet about that issue).
Is there a possibility to stop that behavior?
Thank you.
You should outsource your expensive, long-lasting calculations from the GUI-Thread to a worker thread to prevent your GUI from freezing.
Qt-Documentation: Threading Basics
Good explanation of QThread-usage I found useful: How To Really, Truly Use QThreads
The GUI itself cannot be changed from a worker thread. You have to notify your main-thread about a data-change and update your GUI from there.
You have two options. The more efficient one is to put your calculations into another thread (or multiple threads, there are very few single core CPUs in modern PCs). JSilver's answer has a few links for you.
However, with threads come multitude of threading related things you must learn and take into account. There's a lot of potential for subtle bugs, if you don't know what you're doing. So I would recommend alternative approach as first step, single-threaded. As a bonus, it'll make moving to multi-threaded solution much easier later.
Create a plain sublclass of QObject. Into this QObject, put the state of your calculation as member variables.
Write a slot method into above class, which does a small piece of the calculation, then returns. It should do it's thing at most around 50 ms for good user experience. You can just use a fixed number of iterations in your loop, or use QElapsedTimer to measure time, or whatever. And then, when called again, the method should continue the calculation again for another 50ms. When calculation completes, the method can for example emit a signal with the results.
Add a QTimer with interval 0. Connect the timeout to the slot method described above. Interval 0 here effectively means, Qt will call the method as often as it can. You want this, because you want the calculation to finish as quickly as possible of course. However, since the method returns very soon, then Qt can do other stuff (update GUI etc), before calling your method again.
Once this works, in single thread, you can then learn to do Qt threading and move the worker object to live in another thread, for potentially increased performance. Also then you will have a single-threaded baseline version to compare to, in case you run into threading problems.
Related
I'm struggling with a GUI application in C++.
Clicking buttons activates routines, which may take some time. The window is then unresponsive.
I would like it to keep listening and reactive.
I heard about ISR, which seems unsuitable because I don't want to continue where I left, but rather forget about the aborted procedure and start fresh.
Please don't be harsh on me.
I'd be glad if you can point me to somewhere useful. I've literally spent two hours finding nothing helpful (for me, might be my fault).
The exact solution is going to be very dependent on what you're trying to do, and what (toolkit, etc) you're trying to do it with.
The quick (to give, not to do) answer is to use a separate thread for your work. You have one thread for your GUI stuff, and when the user hits a button you send a message to your worker thread from your GUI thread.
If you're on C++11 or up, you can use std::thread to implement threads. Otherwise, you'll have to use whatever is available on your platform. These APIs are usually quite low level.
std::async has a slightly higher level of operation. The GUI toolkit you're working with might have something. Whatever you choose, it's never going to be as 'simple' as a synchronous, single threaded program.
In general, the earlier you think about your threading strategy in the design of a piece of software, the easier it is to implement. Adding multithreading to a well established program is often very difficult.
Apologies if this is more 'vague' than you were hoping for. Perhaps if you add more details about platform and toolkits, people will be able to make more specific suggestions?
Best of luck!
I'm taking my first steps in GTK+ (C++ and gtkmm more specificaly) and I have a rather conceptual doubts about how to best structure my program. Right now I just want my GUI to show what is happening in my C++ program by printing several values, and since my main thread is halted while the GUI window is running, I've come across solutions that separated both the processing/computing operations and the graphical interface in separate threads. Is this commonly accepted as the best way to do it, not at all, or not even relevant?
Unless you have a good reason, you are generally better off not creating new threads. Synchronization is hard to get right.
GUI programming is event driven (click on a button and something happens). So you will probably need to tie your background processing into the GUI event system.
In the event that your background processing takes a long time, you will need to break it into a number of fast chunks. At the end of each chunk, you can update a progress bar and schedule the next chunk.
This will mean you will need to probably use some state machine patterns.
Also make sure that any IO is non-blocking.
Here's an example of lengthy operation split in smaller chunks using the main loop without additional threads. Lazy Loading using the main loop.
Yes, absolutely! (in response to your title)
The GUI must be run in a separate thread. If you have ever come across those extremely annoying interfaces that lock up while an operation is in progress1, you'd know why it's very important to have the GUI always running regardless of operation happening.
It's a user experience thing.
1 I don't mean the ones that disable some buttons during operation (that's normal), but the ones that everything seems frozen.
This is the reverse: the main thread should be the Gtk one, and the long processing/computing tasks should be done in threads.
The documentation gives a clear example:
https://pygobject.readthedocs.io/en/latest/guide/threading.html
I've tryed to profile one of my application using Qt.
The results I found seemed to show that Qt is a big Thread user. It seems to create and destroy threads a lot. Which is the peak of its memory consumption. Is it true ?
So I've tryed to do some research on "how to optimize a Qt application" but, well I hadn't found anything relevant for now.
So I was wondering if there is any "general way" of programming with Qt that could be optimized. Shall I use the threads in a specific manner ? Can I do anything except respecting C++ standards, -pedantic options in compiler, and so one ?
Generally speaking, if you create and destroy threads a lot, then that's probably not a very good design. Assuming your threads do the same (or similar) things, then having a fixed "pool" of threads that run for as long as it takes and then get put back in the pool when your current code destroys the thread.
Or, let the thread run forever, and feed it data through some suitable IPC.
I would also say that unless you are doing something very special, if something takes less than about a quarter of a second to do, then you shouldn't create a thread to do that. That's not a fixed rule.
Threads as such don't use that much memory, but the stack of each thread may use quite a bit of memory.
If you're creating and destroying QThreads a lot, consider using a QThreadPool or QtConcurrent. These will hold threads in reserve and serve them on demand.
If you're not creating and destroying threads a lot, then your problem is elsewhere.
I'm using TinyThread++ to get clean and simple platform independent control over threading features in my project. I just came upon a situation where I'd like to have responsive synchronized message passing without pegging the CPU, while allowing a thread to continue to do a bit of work on the side while it is idle. Sure, I could simply spawn a third thread to do this "other work" but all I'm missing is a condition variable wait(int ms) type function rather than the wait() that already works great. The idea is that I'd like for it to block only for up to ms milliseconds, so it will be able to time out and perform some actions periodically (during which the thread will not be actively waiting on the condition variable). The idea is that even though it's nice to have the thread sitting there waiting to pounce on any incoming messages, if I give it some task to do on the side which takes only 50 microseconds to execute, and I only need to run that once every second, it definitely shouldn't push me to make yet another thread (and message queue and other resources) to get it done.
Does any of this make sense? I'm looking for suggestions on how i might go about implementing this. I'm hoping adding a couple of lines to the TinyThread code can provide me with this functionality.
Well the source code for the wait function isn't very complicated so making the required modificiations looks simple enough:
The linux implementation relies on the pthread_cond_wait function
which can trivially be changed to the pthread_cond_timedwait
function. Do read the documentation carefully in case I forgot about any minutias.
On the windows side of things, it's a little more
complicated and I'm no expert on multithreading on windows. That
being said, if there's a timed version of the _wait function (I'm pretty sure there is),
changing that should work just fine. Again, read over the documentation carefully before doing any modifications.
Now before you go off and do these modifications, I don't think what you're trying to do is a good idea. The main advantage of using threads is to conceptually seperate different tasks. Trying to do multiple things in a single thread is a bit like trying to do multiple things in a single function: it complicates the design and makes things harder to debug. So unless the overhead of creating a new thread is provably too great or unless the resulting code remains simple and easy to understand, I'd split it up into multiple threads.
Finally, I get the feeling that you might not be aware that condition variables can return spuriously (returns without anybody having done any signalling or returns when the condition is still false). So just in case, I'd suggest reviewing the usage examples and making sure you understand why those loops are there.
I am creating an application which must execute a function that takes too long (lets call it slowfunc()), which is a problem, since my application is working with a live video feed. By running this function every frame, the frame rate is severely affected.
Is there a way to run slowfunc() in the background without using threading? I don't necessarily need it to run every frame, but every time it finishes, I'd like to examine the output. The only thing I can think of right now is to split up slowfunc() into several "mini-functions" which would each take approximately an equal amount of time, then run one minifunction per frame. However, slowfunc() is a relatively complex function, and I feel that there should be (hopefully is) a way to do this simply.
EDIT: I can't use threading because this program will eventually be used on a tiny robot processor which probably will not support threading. I guess I can use "cooperative multitasking". Thanks for your help!
Run it in a thread and after the calculation is finished, make the thread sleep until another calculation is ready to be run. That way you are not hit with the initialization of the thread every time.
You're asking for simaltaneous execution. The two ways to do this are -:
a) Multi-threading -: Create another thread to run on a background.
b) MUlti-processing -: Create another process . Take all inputs required for the function via a shared memory model. Create a synchronisation mechanism with original process(parent process). Execute this function.
It is normally prefered to use the 1st one. Faster execution.
The 2nd one guarantees that if the function crashes your parent process still runs. Although, that is a bit irrelevant since, why would you want your child(function) to crash. This needs more memory.