I am working on a program using Qt, and some of my code is based on Windows samples. The problem I'm experiencing and something that I don't quite understand is how the same code blocks my Qt GUI while it runs fully in a Windows application.
Here is an example. I have a program that receives some data from the camera, does some processing on it, and then displays it on the screen. There is something like this in the Windows sample:
// Create an event with these self-explanatory parameters // This event signals when the next frame is ready to process HANDLE frameEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr) // Now run a while loop which magically doesn't block HANDLE hEvents[1]; while (WM_QUIT != msg.message) { hEvents[0] = frameEvent; DWORD dwEvent = MsgWaitForMultipleObjects(1, hEvents, FALSE, INFINITE, QS_ALLINPUT); // If we have our event run some processing if (WAIT_OBJECT_0 == dwEvent) { update(); } // Else handle input or whatever }
The update function looks something like this:
if (WAIT_OBJECT_0 = WaitForSingleObject(frameEvent, 0) { getTheFrame(); processTheFrame(); drawTheFrame(); }
If I try to implement it in the same way as in Qt, everything will freeze, and the while loop will just start forever. The solution I have is to start the loop in a separate thread (QThread) and emit a signal when a new frame is ready, for example:
void Worker::run() { running_ = true; while (running_) { if (WaitForSingleObject(frameEvent, 0) == WAIT_OBJECT_0) { emit signalFrame(); }
Then the signal is connected to the slot, which performs a similar task to the Update() method from the sample window.
Now this works great, but only as long as processing one frame can be done before the next frame is available.
Since my processing has become more complex and slower than the frame rate of the camera, the program simply stops responding. The exact code in the Windows sample still works fine, the frame rate just drops, but everything is drawn, and the graphical interface remains responsive.
Can someone explain what is happening and what could be a possible solution?