This is my scenario: I have a dll (with Qt in the back-end, and with no event loop started). I am able to perform the signal-slot communication with-in this dll (there is a only one thread). I would like to use the facilities of QFileSystemWatcher in this dll. But it looks like, QFileSystemWatcher starts its own thread, and it is not able to communicate to my main thread since there is no event process.
So, basically I need a way to start the event processing without being blocked !
So, basically I need a way to start the event processing without being blocked !
So, basically you want to use QEventLoop features without using the QEventLoop based on the comment discussion. The QEventLoop has to be "blocking", inherently, in order to actually have an event loop.
You could always create a "blocking" thread with the event loop inside, but then your signal-slot management might be tied to that particular thread.
This is not the usual way of using an event loop, but depending on your concrete scenario, it might be sufficient in this special case.
Related
Back to stackoverflow with another question after hours of trying on my own haha.
Thank you all for reading this and helping in advance.
Please note the console program has following functionalities:
connect to a frame grabber
apply some configs
store the incoming data (640 * 480 16-bit grayscale imgs) in a stream of buffers inside a while loop
Exits the while loop upon a key press.
disconnect from device
And I'm only adding the displaying the images functionality on the MFC GUI app. In short,
i) Converting a console app to an MFC app (dialog based)
ii) decided to use thread for displaying images, but DK how to properly exit from thread when there are certain tasks to be done (such as call disconnectFromDevice(); freeBuffers();, etc) before exiting the thread.
iii) have tried making the while loop condition false but didn't work
( I actually want this to be a callback function that's called repeatedly but IDK how to implement it inside a thread)
iv) forcing AfxEndThread didn't work and it's not even the way it should be done (I think).
So my question is,
1. Are you supposed to use a while loop to excuete a certain job that should repeatedly be done? If not, do you have to implement a callback inside a thread? Or use Windows message loop? Why and how? Please provide a hello-world-like sample code example
(for example, you are printing "hello world" repeatedly inside a thread with a condtion in an MFC GUI app. How do you update or check the condition to end the thread if you can't just AfxEndThread() inside the threadproc)
2. If it's ok with a while, how do you exit from the while loop, in other words how do you properly update the exit condition outside the thread the while loop's in?
Please refer to the source code in the provided link
ctrl+F OnBnClickedConnectButton, AcquireImages and OnBnClickedDisconnectButton
https://github.com/MetaCortex728/img_processing/blob/main/IR140Dlg.cpp
Worker threads do not have message-queues, the (typically one and only) UI one does. The message-queue for a thread is created by the first call of the GetMessage() function. Why use messages to control processing in a worker thread? You would have to establish a special protocol for this, defining custom messages and posting them to the queue.
Worker threads can be implemented as a loop. The loop can be terminated based on various conditions, like failures to retrieve any data or request from the user. You can simply exit the thread proc to terminate the thread's execution. If the thread doesn't respond it may have stuck (unless it performs a really lengthy operation) and the UI thread must provide some mechanism to kill it. That is first request termination and if it doesn't respond within some set time then kill it.
The condition mechanism to terminate should best be some synchronization object (I would recommend a manual-reset event), interlocked variable or a simple boolean which you should access and set using a critical section.
Some considerations:
You pass a parameter block to the thread. Make sure that it remains alive throughout the thread's lifetime. For example, it should NOT be a local variable in a function that exits before the thread's termination.
The loop must be "efficient", ie do not loop infinitely if data are not available. Consider using blocking functions with timeouts, if available.
Resource management (eg connecting/disconnecting, allocating/releasing etc) should best be performed by the same thread.
An alternative implementation can be APCs. Then the thread's proc function is a while(!bTerminate) { SleepEx(INFINITE, TRUE); } loop, and other threads issue requests using a the QueueUserAPC() function.
The AfxEndThread(0) call in OnBnClickedDisconnectButton() is wrong, it terminates the current thread, which in this case is the main (UI) thread. Check the documentation.
A sidenote, my suggestion about the project type is not a dialog-based application but instead a normal MFC application without a document class (uncheck the Document/View architecture support option), as it offers features like menus, toolbars and the like, and most importantly the ON_UPDATE_COMMAND_UI handlers.
I'm on some c++ mobile product, but I need my apps main thread is still running without any blocking when doing some heavy work on the background thread and run back on main thread. But I realized there is no runOnMainThread/runOnUIThread in c++ thread api. I trying to figure it out the issue and found that need to depend library, or create your own thread event queue. Although it is good, but i am thinking to have a behavior which can runOnUIThread.
How it does not work: the mentioned library creates a timer, installs a SIGALRM signal handler and dispatches queued tasks when signals are fired. This allows tasks being processed on the main thread even when it is busy. However POSIX permits only a small set of async-signal-safe functions to be invoked inside of signal handler. Running arbitrary с++ code inside of signal handler violates that restriction and leaves application in hopelessly doomed state.
After some research and development, I've created a library called NonBlockpp
it is a small c++ library to allow c++ mobile application able to process the heavy and time consuming task on background and back to Main thread again, It’s been tested and fired the main thread event.
It also allow to save the tasks and fire them later, all the task has no blocking each other and thread safety.
How it works:
If you found any query or suggestion, please don't hesitate to raise an issue and we can discuss it together.
The project has rectify from signal to pollEvent due to signal handler might not be safe to use.
Please take a look the new changed.
NonBlockpp
Usage
More precisely, the question should be:
What's the difference between connecting the signal QTimer::timeout to my working function and creating a worker thread with QThread?
I am writing a program which receives streaming data in main thread (the signal is generated by QIODevice::readread())and processes them concurrently. For now I start a QTimer constantly firing signal QTimer::timeout, and the signal is connected to a working function in main thread which does the data processing stuff. This is how I achieve the concurrency.
I wonder if this approach different from creating another thread with QThread, since the idea I've found in this topic is very simliar to what I've done. The only difference is that the accepted answer creates another thread and moves timer and worker class on it. Besides the difference, I can't see any necessity of using a thread in my case.
In my case (receiving data in main thread and processing them concurrently), am I doing OK using QTimer or should I create a QThread? I am quite new to multi-threading, and if I misunderstand something, please help correct me. Thank you.
[Edit]:
I don't know what's the difference/advantage of creating a new thread to process the data. For now, everything is doing in one thread: I keep storing data in a queue and dequeue them one by one in a function triggered by QTimer::timeout.
What's the difference between connecting the signal QTimer::timeout to my working
function and creating a worker thread with QThread?
When you connect some signal/slot pair from the objects which has the same thread affinity, then the connection is direct. What it means is in your case, the main thread creates the timer, and also contains the slot, so the signal will be emitted in the main thread and also will be processed in the main thread (as the slot is also in the main thread).
When you connect some signal/slot pair from the objects which has the different thread affinity, then the connection is queued. That means signal emission and slot execution will run in different threads.
You are not really achieving concurrency, the timer signal and processing slot are executing in main thread sequentially.
So here are your options:
If you want to process data in main thread, current code is ok.
If you want to emit timeout in main thread and process data in different thread then create new class with the processing method and use moveToThread with object of that class.
The link you provided really has a different situation. In your case (correct me if I am wrong), you process data only when data is available, not just after a specified time. Your situation is much like traditional producer/consumer problem. My proposal is to not use QTimer at all. Instead create a new class with a slotwhich will process data. Then emit a signal from main thread when data is available, and connect if to the processing slot. You will achieve real concurrency. In this case you will need to implement locking for shared data access, it is easy in Qt, you can just use QMutexLocker
First, a little background:
One of the fundamental ideas behind threads is that a thread can only do one thing at a time. It may be updating the GUI, or processing data, or communicating with a remote server, but it can't be doing all those things at once.
That's where multi-threading comes in. You probably want your computer to be doing many things at once (watching videos, browsing the web, listening to music, and writing code all at the same time). The computer allows you to do that by scheduling each of these tasks on a separate threads and switching between them in periodic intervals.
In the old days, before multi-core processors, this was achieved solely by multitasking (the processor would interrupt the currently executing thread, switch to another thread context and execute the other thread for a while before switching again). With modern processors, you can have several threads executing at the EXACT same time, one on each core. This is typically referred to as multiprocessing.
Now, back to your question:
A thread can only do one thing at a time and, if you use a timer, you are using the main (AKA GUI) thread to process your data. This thread is typically responsible for responding to OS events and updating the GUI (hence GUI thread). If you don't have a lot of data to process, it's typically OK to do so on the GUI thread. However, if the data processing time has a chance of growing, it is recommended to execute such processing on a separate thread to make sure that the UI remains responsive (and so that you don't get the annoying "Your program is not responding" message from the OS). Basically, if data processing can take longer than ~200ms, it is recommended to execute the processing on a separate thread so that the user doesn't feel like the GUI is "stuck".
I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.
At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread.
Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password.
Does anyone know a suitable mechanism for doing this?
My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (emit passwordRequestedEvent(passwordRequest);. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made..
Is this sort of thing sensible? or is there another option?
Using signals to send messages between threads is fine, if you don't like using the Condition Variable, then you can send signals in both directions in a more-or-less asynchronous manner: this might be a better option if you want to continue processing network stuff while you wait for a reply from the GUI.
I'm importing a portion of existing code into my Qt app and noticed a sleep function in there. I see that this type of function has no place in event programming. What should I do instead?
UPDATE: After thought and feedback I would say the answer is: call sleep outside the GUI main thread only and if you need to wait in the GUI thread use processEvents() or an event loop, this will prevent the GUI from freezing.
It isn't pretty but I found this in the Qt mailing list archives:
The sleep method of QThread is protected, but you can expose it like so:
class SleeperThread : public QThread
{
public:
static void msleep(unsigned long msecs)
{
QThread::msleep(msecs);
}
};
Then just call:
SleeperThread::msleep(1000);
from any thread.
However, a more elegant solution would be to refactor your code to use a QTimer - this might require you saving the state so you know what to do when the timer goes off.
I don't recommend sleep in a event based system but if you want to ...
You can use a waitcondition, that way you can always interrupt the sleep if neccesary.
//...
QMutex dummy;
dummy.lock();
QWaitCondition waitCondition;
waitCondition.wait(&dummy, waitTime);
//...
The reason why sleep is a bad idea in event based programming is because event based programming is effectively a form on non-preemptive multitasking. By calling sleep, you prevent any other event becoming active and therefore blocking the processing of the thread.
In a request response scenario for udp packets, send the request and immediately wait for the response. Qt has good socket APIs which will ensure that the socket does not block while waiting for the event. The event will come when it comes. In your case the QSocket::readReady signal is your friend.
If you want to schedule an event for some point of time in the future, use QTimer. This will ensure that other events are not blocked.
It is not necessary to break down the events at all. All I needed to do was to call QApplication::processEvents() where sleep() was and this prevents the GUI from freezing.
I don't know how the QTs handle the events internally, but on most systems at the lowest level the application life goes like this: the main thread code is basically a loop (the message loop), in which, at each iteration, the application calls a function that gives to it a new message; usually that function is blocking, i.e. if there are no messages the function does not return and the application is stopped.
Each time the function returns, the application has a new message to process, that usually has some recipient (the window to which is sent), a meaning (the message code, e.g. the mouse pointer has been moved) and some additional data (e.g. the mouse has been moved to coords 24, 12).
Now, the application has to process the message; the OS or the GUI toolkit usually do this under the hood, so with some black magic the message is dispatched to its recipient and the correct event handler is executed. When the event handler returns, the internal function that called the event handler returns, so does the one that called it and so on, until the control comes back to the main loop, that now will call again the magic message-retrieving function to get another message. This cycle goes on until the application terminates.
Now, I wrote all this to make you understand why sleep is bad in an event driven GUI application: if you notice, while a message is processed no other messages can be processed, since the main thread is busy running your event handler, that, after all, is just a function called by the message loop. So, if you make your event handler sleep, also the message loop will sleep, which means that the application in the meantime won't receive and process any other messages, including the ones that make your window repaint, so your application will look "hang" from the user perspective.
Long story short: don't use sleep unless you have to sleep for very short times (few hundreds milliseconds at most), otherwise the GUI will become unresponsive. You have several options to replace the sleeps: you can use a timer (QTimer), but it may require you to do a lot of bookkeeping between a timer event and the other. A popular alternative is to start a separate worker thread: it would just handle the UDP communication, and, being separate from the main thread, it would not cause any problem sleeping when necessary. Obviously you must take care to protect the data shared between the threads with mutexes and be careful to avoid race conditions and all the other kind of problems that occur with multithreading.