c++ jump to eventhandler - c++

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!

Related

Qt C++ "keine Rückmeldung" - Error in GUI during long calculations

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.

Should GTK+ interface run in a separate thread?

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

An event system - like signal / slot in Qt without forking - C++

I would like to know how to design a system that can offer a solid framework to handle signals and the connection between the signal/s and the method/s without writing a really unpleasant cycle that iterates over and over with some statement for forking the flow of the application.
In other words I would like to know the theory behind the signal slot mechanism of Qt or similar.
I'm naming Qt for no particular reason, it's just probably one of the most used and well tested library for this so it's a reference in the C++ world, but any idea about the design of this mechanism will be good.
Thanks.
At a high level, Qt's signal/slots and boost's signal library work like the Observer Pattern (they just avoid needing an Observer base class).
Each "signal" keeps track of what "slots" are observing it, and then iterates over all of them when the signal is emitted.
As for how to specifically implement this, the C++ is pretty similar to the Java code in the Wikipedia article. If you want to avoid using an interface for all observers, boost uses templates and Qt uses macros and a special pre-compiler (called moc).
It sounds like you are asking for everything but without any losses.
There are a few general concepts that I am aware of for handling asynchronous input and changes such as "keys being pressed" and "touch events" and "an object that changes its own state".
Most of these concepts and mechanisms are useful for all sorts of program flow and can cross lots of boundaries: process, thread, etc. This isn't the most exhaustive list but they cover many of the ones I've come across.
State Machines
Threads
Messages
Event Loops
Signals and Slots
Polling
Timers
Call Back Functions
Hooking Input
Pipes
Sockets
I would recommend researching these in Wikipedia or in the Qt Documentation or in a C++ book and see what works or what mechanism you want to work into your framework.
Another really good idea is to look at how programming architects have done it in the past, such as in the source of Linux or how the Windows API lets you access this kind of information in their frameworks.
Hope that helps.
EDIT: Response to comment/additions to the question
I would manage a buffer/queue of incoming coordinates, and have an accessor for the latest coordinate. Then I would keep track of events such as the start of a touch/tap/drag and the end of one, and have some sort of timer for when a long touch is performed, and a minimum change measurement for when a dragged touch is performed.
If I am using this with just one program, I would try to make a interface that is similar to what I could find in use. I've heard of OpenSoundControl being used for this kind of input. I've set up a thread that collects the coordinates and keeps track of the events. Then I poll for that information in the program/class that needs to use it.

How to convert my project to become a multi threaded application

I have a project and I want to convert it to multi-threaded application. What are the things that can be done to make it a multi threaded application
List out things to be done to convert into multithreaded application
e.g mutex lock on shared variables.
I was not able to find a question which list all those under single hood.
project is in C
Single threaded application need not be concerned about being thread safe.
This issue arises when you have multiple threads which are trying to access a commonly shared resource. At that time, you must be concerned.
So, no need to worry.
EDIT (after question been edited ) :
You need to go through the following links.
Single threaded to multithreaded application
Single threaded to multithreaded application - What we need to consider ?
Advice - Single threaded to multithreaded application
Also a good advice for converting single to multithreaded application.Check out.
Single threaded -> Multithreaded application :: Good advice.
The big issue is that, in general, when designing your application it is very difficult to choose single thread and then later on add multi-threading. The choice is fundamental to the design idioms you are going to strive towards. Here's a brief but poor guide of some of the things you should be paying attention towards and how to modify your code (note, none of these are set in stone, there's always a way around):
Remove all mutable global variables. I'd say this goes for single threaded applications too but that's just me.
Add "const" to as many variables as you can as a first pass to decide where there are state changes and take notes from the compilation errors. This is not to say "turn all your variables to const." It is just s simple hack to figure out where your problem areas are going to be.
For those items which are mutable and which will be shared (that is, you can't leave them as const without compilation warnings) put locks around them. Each lock should be logged.
Next, introduce your threads. You're probably about to suffer a lot of deadlocks, livelocks, race conditions, and what not as your single threaded application made assumptions about the way and order your application would run.
Start by paring away unneeded locks. That is, look to the mutable state which isn't shared amongst your threads. Those locks are superfluous and need to go.
Next, study your code. At this point, determining where your threaded issues are is more art than science. Although, there are decent principals about how to go about this, that's about all I can say.
If that sounds like too much effort, it's time to look towards the Actor model for concurrency. This would be akin to creating several different applications which call one another through a message passing scheme. I find that Actors are not only intuitive but also massively friendly to determining where and how you might encounter threading issues. When setting up Actors, it's almost impossible not to think about all the "what ifs."
Personally, when dealing with a single threaded to multi threaded conversion, I do as little as possible to meet project goals. It's just safer.
This depends very heavily on exactly how you intend to use threads. What does your program do? Where do you want to use threads? What will those threads be doing?
You will need to figure out what resources these threads will be sharing, and apply appropriate locking. Since you're starting with a single-threaded application, it's a good idea to minimize the shared resources to make porting easier. For example, if you have a single GUI thread right now, and need to do some complex computations in multiple threads, spawn those threads, but don't have them directly touch any data for the GUI - instead, send a asynchronous message to the GUI thread (how you do this depends on the OS and GUI library) and have it handle any changes to GUI-thread data in a serialized fashion on the GUI thread itself.
As general advice, don't simply add threads willy-nilly. You should know exactly which variables and data structures are shared between threads, where they are accessed, and why. And you should be keeping said sharing to the minimum.
Without a much more detailed description of your application, it's nearly impossible to give you a complete answer.
It will be a good idea to give some insight in your understanding of threading aswell.
However, the most important is that each time a global variable is accessed or a pointer is used, there's a good chance you'll need to do that inside of a mutex.
This wikipedia page should be a good start : http://en.wikipedia.org/wiki/Thread_safety

What should I know about multithreading and when to use it, mainly in c++

I have never come across multithreading but I hear about it everywhere. What should I know about it and when should I use it? I code mainly in c++.
Mostly, you will need to learn about MT libraries on OS on which your application needs to run. Until and unless C++0x becomes a reality (which is a long way as it looks now), there is no support from the language proper or the standard library for threads. I suggest you take a look at the POSIX standard pthreads library for *nix and Windows threads to get started.
This is my opinion, but the biggest issue with multithreading is that it is difficult. I don't mean that from an experienced programmer point of view, I mean it conceptually. There really are a lot of difficult concurrency problems that appear once you dive into parallel programming. This is well known, and there are many approaches taken to make concurrency easier for the application developer. Functional languages have become a lot more popular because of their lack of side effects and idempotency. Some vendors choose to hide the concurrency behind API's (like Apple's Core Animation).
Multitheaded programs can see some huge gains in performance (both in user perception and actual amount of work done), but you do have to spend time to understand the interactions that your code and data structures make.
MSDN Multithreading for Rookies article is probably worth reading. Being from Microsoft, it's written in terms of what Microsoft OSes support(ed in 1993), but most of the basic ideas apply equally to other systems, with suitable renaming of functions and such.
That is a huge subject.
A few points...
With multi-core, the importance of multi-threading is now huge. If you aren't multithreading, you aren't getting the full performance capability of the machine.
Multi-threading is hard. Communicating and synchronization between threads is tricky to get right. Problems are often intermittent, hard to diagnose, and if the design isn't right for multi-threading, hard to fix.
Multi-threading is currently mostly non-portable and platform specific.
There are portable libraries with wrappers around threading APIs. Boost is one. wxWidgets (mainly a GUI library) is another. It can be done reasonably portably, but you won't have all the options you get from platform-specific APIs.
I've got an introduction to multithreading that you might find useful.
In this article there isn't a single
line of code and it's not aimed at
teaching the intricacies of
multithreaded programming in any given
programming language but to give a
short introduction, focusing primarily
on how and especially why and when
multithreaded programming would be
useful.
Here's a link to a good tutorial on POSIX threads programming (with diagrams) to get you started. While this tutorial is pthread specific, many of the concepts transfer to other systems.
To understand more about when to use threads, it helps to have a basic understanding of parallel programming. Here's a link to a tutorial on the very basics of parallel computing intended for those who are just becoming acquainted with the subject.
The other replies covered the how part, I'll briefly mention when to use multithreading.
The main alternative to multithreading is using a timer. Consider for example that you need to update a little label on your form with the existence of a file. If the file exists, you need to draw a special icon or something. Now if you use a timer with a low timeout, you can achieve basically the same thing, a function that polls if the file exists very frequently and updates your ui. No extra hassle.
But your function is doing a lot of unnecessary work, isn't it. The OS provides a "hey this file has been created" primitive that puts your thread to sleep until your file is ready. Obviously you can't use this from the ui thread or your entire application would freeze, so instead you spawn a new thread and set it to wait on the file creation event.
Now your application is using as little cpu as possible because of the fact that threads can wait on events (be it with mutexes or events). Say your file is ready however. You can't update your ui from different threads because all hell would break loose if 2 threads try to change the same bit of memory at the same time. In fact this is so bad that windows flat out rejects your attempts to do it at all.
So now you need either a synchronization mechanism of sorts to communicate with the ui one after the other (serially) so you don't step on eachother's toes, but you can't code the main thread part because the ui loop is hidden deep inside windows.
The other alternative is to use another way to communicate between threads. In this case, you might use PostMessage to post a message to the main ui loop that the file has been found and to do its job.
Now if your work can't be waited upon and can't be split nicely into little bits (for use in a short-timeout timer), all you have left is another thread and all the synchronization issues that arise from it.
It might be worth it. Or it might bite you in the ass after days and days, potentially weeks, of debugging the odd race condition you missed. It might pay off to spend a long time first to try to split it up into little bits for use with a timer. Even if you can't, the few cases where you can will outweigh the time cost.
You should know that it's hard. Some people think it's impossibly hard, that there's no practical way to verify that a program is thread safe. Dr. Hipp, author of sqlite, states that thread are evil. This article covers the problems with threads in detail.
The Chrome browser uses processes instead of threads, and tools like Stackless Python avoid hardware-supported threads in favor of interpreter-supported "micro-threads". Even things like web servers, where you'd think threading would be a perfect fit, and moving towards event driven architectures.
I myself wouldn't say it's impossible: many people have tried and succeeded. But there's no doubt writting production quality multi-threaded code is really hard. Successful multi-threaded applications tend to use only a few, predetermined threads with just a few carefully analyzed points of communication. For example a game with just two threads, physics and rendering, or a GUI app with a UI thread and background thread, and nothing else. A program that's spawning and joining threads throughout the code base will certainly have many impossible-to-find intermittent bugs.
It's particularly hard in C++, for two reasons:
the current version of the standard doesn't mention threads at all. All threading libraries and platform and implementation specific.
The scope of what's considered an atomic operation is rather narrow compared to a language like Java.
cross-platform libraries like boost Threads mitigate this somewhat. The future C++0x will introduce some threading support. But boost also has good interprocess communication support you could use to avoid threads altogether.
If you know nothing else about threading than that it's hard and should be treated with respect, than you know more than 99% of programmers.
If after all that, you're still interested in starting down the long hard road towards being able to write a multi-threaded C++ program that won't segfault at random, then I recommend starting with Boost threads. They're well documented, high level, and work cross platform. The concepts (mutexes, locks, futures) are the same few key concepts present in all threading libraries.