MFC Threading Issue - The program doesnt end after all threads are completed - multithreading

I have created a Single Dialog application which basically does a series of complex calculation. The application was first created as a Win32 console application and later I decided to add a progressbar and then I converted the console application to a Single Dialog based application. The dialog has a progressbar on it. in OnInitDialog() function of the dialog, I start the calculations. The calculations are running on a worker thread. This thread is created by calling _beginthreadex function. The progressbar is updated by the thread by posting messages to the Dialog by using PostMessage. After the thread has completed execution, I call CDialog::OnOK() function to close the dialog. The issue is that, even after the dialog is closed, the application is not end immediately. It takes nearly 2 seconds to close the application even though the dialog is closed.
Any help to solve this issue is highly appreciated.
Thanks.

It's because your worker thread is still running. The application will not terminate until all threads are finished running. Since your UI thread closes before the worker thread, the window may be hidden, but the process does not terminate until the worker thread has completed its work.

The worker thread might be still running. To make sure that the thread is stopped use events to signal . you can signal an event to kill the thread when the user presses close button in the dialog.
You can check whether the event is signaled inside your complex calculation (may be a loop) and break from it. Thus stopping the thread without any issues.
while(true)
{
//Some complex task
DWORD dwWaitResult;
dwWaitResult = WaitForSingleObject(hwndShutdownEvent,0);
if (WAIT_OBJECT_0 == dwWaitResult)
{
break;
}
}

Related

Why can a sub-classed QThread simply fail to start?

This is using a sub-classed QThread based on the ideas expressed in the whitepaper "QThreads: You were not doing so wrong". It does not have an event loop, nor does it have slots. It just emits signals and stops. In fact its primary signal is the QThread finished one.
Basically I have a Qt using a background thread to monitor stuff. Upon finding what it is looking for, it records its data, and terminates.
The termination sends a signal to the main event loop part of the application, which processes it, and when done, starts the background anew. I can usually get this working for tens of seconds, but then it just seems to quit.
It seems that when the main application tries to start the thread, it doesn't really run. I base this on telemetry code that increments counters as procedures get executed.
basically
//in main application. Setup not shown.
//background points to the QThread sub-class object
void MainWindow::StartBackground()
{
background->startcount++;
background->start();
if ( background->isRunning() )
{
background->startedcount++;
}
}
//in sub-classed QThread
void Background::run()
{
runcount++;
//Do stuff until done
}
So when I notice that it seems that my background thread isn't running, by watching Process Explorer, I cause the debugger to break in, and check the counts. What I see is that startcount and startedcount are equal. And have a value of one greater than runcount
So I can only conclude that the thread didn't really run, but I have been unable to find out any evidence of why.
I have not been able to find documentation on QThreads not starting do to some error condition, or what evidence there is of such an error.
I suppose I could set up a slot to catch started from the thread. The starting code could loop on a timed-out semaphore, trying again and again until the started slot actually resets the semaphore. But it feels ugly.
EDIT - further information
So using the semaphore method, I have a way to breakpoint on failure to start.
I sampled isFinished() right before I wanted to do start(), and it was false. After my 100ms semaphore timeout it became true.
So the question seems to be evolving into 'Why does QThread sometimes emit a finished() signal before isFinished() becomes true?'
Heck of a race condition. I'd hate to spin on isFinished() before starting the next background thread.
So this may be a duplicate of
QThread emits finished() signal but isRunning() returns true and isFinished() returns false
But not exactly, because I do override run() and I have no event loop.
In particular the events 8 and 9 in that answer are not in the same order. My slot is getting a finished() before isFinished() goes true.
I'm not sure an explicit quit() is any different than letting run() return;
It sounds as if you have a race condition wherein you may end up trying to restart your thread before the previous iteration has actually finished. If that's the case then, from what I've seen, the next call to QThread::start will be silently ignored. You need to update your code so that it checks the status of the thread before restarting -- either by calling QThread::isFinished or handling the QThread::finished signal.
On the other hand... why have the thread repeatedly started/stopped. Would it not be easier to simply start the thread once? Whatever code is run within the context of QThread::run can monitor whatever it monitors and signal the main app when it finds anything of note.
Better still. Separate the monitor logic from the thread entirely...
class monitor: public QObject {
.
.
.
};
QThread monitor_thread;
monitor monitor;
/*
* Fix up any signals to/from monitor.
*/
monitor.moveToThread(&monitor_thread);
monitor_thread.start();
The monitor class can do whatever it wants and when it's time to quit the app can just call monitor_thread::quit.
There is a race condition in the version of Qt I am using. I don't know if it was reported or not before, but I do not have the latest, so it's probably moot unless I can demonstrate it in the current version.
Similar bugs were reported here long ago:
QThread.isFinished returns False in slot connected to finished() signal
(the version I use is much more recent than Qt 4.8.5)
What more important is I can workaround it with the following code
while ( isRunning() )
{
msleep(1);
}
start();
I've run a few tests, and it never seems to take more than 1ms for the race condition to settle. Probably just needs a context switch to clean up.

How JavaFX application thread works?

I have a problem with Java FX application thread. Here is a pseudo-code:
showMenu();
//Contoller which waits for action(pressing button)...
showLoadingPic();
Thread.sleep(2000);
showMap();
The problem is that the sleep occurs in window which is displayed in showMenu(), showLoadingPic() is not shown at all, and at the end window in showMap() is shown.
The scene in showLoadingPic has a progress bar which runs 2 secs which is the same time as Thread.sleep(2000).
So it seems like javafx application thread blocks showLoadingPic() and showLoadingPic() runs at background.
Can somebody help me to fix this??
Thank you in advance!
There is a Java FX event dispatch thread, which handle all GUI-related tasks. You must update all UI components in this thread.
Long-running tasks, like Thread.sleep should never be executed in this thread, since windows will hang, and the GUI will be frozen.
Execute all your code in the application main thread, and perform only GUI tasks in JavaFX thread, by calling Platform.runLater.
References on this topic:
Concurrency in JavaFX, from Oracle
Related SO question

MFC main thread to wait for another thread to end

I am trying to use MFC to create a tool. This tool main job is to sort data. Well, I found that when the tool is sorting, since there is only main thread; therefore, while it is doing sorting work, no dialog boxes can be moved or clicked. Hence, I created another thread to do sorting work and works fine.
But there is another problem after I used a thread. I don't how to make main thread to wait for the sorting thread. I want to do something after sorting thread is done, but right now, main thread just moves onto the next procedures without waiting for sorting thread to finish its work.
Here is snippet
AfxBeginThread(processfiles, tVals) // A thread do its work.
// below I want to do something with the result I got from the thread above.
//But main thread just do its work separately without waiting for the thread to finish its work.
.
please help thanks!!
So write code to do that. Pop up a dialog box. Indicate that the sorting is taking place. Do whatever you want. Have the other thread send your thread a signal when it's done, say by sending you a message with PostMessage.

Thread scheduling issue with MFC and AfxBeginThread

I'm creating a worker thread in MFC with AfxBeginThread, but the thread is not getting scheduled. Here's the code:
CWinThread* worker = AfxBeginThread(initialUpdateWorkerThread, this);
DWORD dwExitCode = 0;
while(GetExitCodeThread(worker->m_hThread, &dwExitCode))
{
if(dwExitCode != STILL_ACTIVE)
break;
::Sleep(100);
}
When I run this, this loop just livelocks because initialUpdateWorkerThread is never called (I've put break points and message boxes at the top of it) so dwExitCode is always STILL_ACITVE. But if I put in a call to AfxMessageBox before the loop but after AfxBeginThread then the function is called. This makes me think that somehow I'm not calling the right function to get the thread scheduled, but a call to AfxMessageBox causes it to get scheduled.
How can I force the thread to be scheduled? I would think sleep would do that, but in this case it doesn't seem to.
Your worker thread is probably trying to send your main thread a message, but since you aren't processing messages on on the main thread, the worker thread simply waits. You can confirm this by simply breaking into the debugger to see what the worker thread is doing.

Crash after pop'ing stack while a threaded NSURLConnection is open

Error Log says:
bool _WebTryThreadLock(bool), 0x3c689f0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
App structure:
worker threads are detached from the MainThread as new data is needed via user interaction, each worker thread feeds data into its own slot in an array. The problem arises only when I use the NavigationController to go "back" to the previous view WHILE a thread is still gathering data. I've tried to send a [NSThread exit] to each thread upon viewWillDisappear thats not going to work...
Any suggestions on thread clean-up upon poppin' the view controller?
So apparently i needed to build in checks to the runloop as well as the didRecieveData loop to watch for a global variable to indicate if the view has disappeared. This in turn needs to toggle the global var, causing all open threads to cancel the connection as well as exit the thread.

Resources