A sleep in thread causes memory leak - c++

I peek into my ancestor's code and found out a leak in the following situation:
1) Launch application
b) After application is launched, close the applicaiton within 4 secs
The leak message:
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {58509} client block at 0x016DFA30, subtype c0, 68 bytes long.
Subsequently, I went through the code, found out the suspicious point of cause at a 4secs of sleep at controlling function of worker thread.
The test program:
UINT InitThread(LPVOID pParam)
{
Sleep(4000); //4000 is the default value, it reads from a registry key.
CMyMFCTestProjectDlg* pTest = (CMyMFCTestProjectDlg*)pParam;
pTest->DoSomething();
return 0; //--> Exit thread
}
BOOL CMyMFCTestProjectDlg::OnInitDialog() {
...
AfxBeginThread(InitThread, this);
...
}
If I reduce/remove the sleep timer, the leak will be solved.
However, I would like to know how does it happen. Either due to worker thread or GUI thread termination? Will worker thread exits after GUI thread will cause this problem?
Anyone can cheer up my day by helping me to explain this? I'm lost....

It sounds like the worker thread is not given a chance to close itself properly after your app closes, since the process ends before it exits. The operating system is usually pretty good at cleaning up resources on its own, so it may not be a problem. However, it's probably best if you wait for that thread to exit before allowing the application to shut down. Though it sounds like that that will cause a 4 second delay in the shutdown of your app.
If that's unacceptable, you will have to add some mechanism to the thread, to receive the shutdown event from the apps main thread. For example, if you replace the worker threads "sleep", with a WaitForSingleObject of an event:
DWORD res = WaitForSingleObject(
shutdownEvent,
4000); // timeout
if(res == WAIT_OBJECT_0)
{
// received the shutdownEvent, exit
return 0;
}
// The delay has elapsed, continue with rest of thread.
. . .
Then, when your are shutting down in your main thread, set the event, then wait for the thread to exit, it should exit almost immediately:
SetEvent(this->shutdownEvent);
WaitForSingleObject(pThread->m_hThread, INFINITE); // pThread is returned from AfxBeginThread

You should shutdown your threads gracefully before your process goes away. You can either have the main thread wait for the other thread(s) to exit or have the main thread signal the other thread(s) to exit.

68 bytes?
If the application does actually shut down, ie. has disappeared from the task manager 'Applications' and 'Processes', and the only effect of this 'leak' is to issue a debug message on early close, just turn the debug off and forget about it.
It's likely an abberation of MFC shutdown, some struct that cannot be safely freed during shutdown and is left around for the OS to clean up.
With the 99.9% of apps that are not continually restarted/stopped, a 68-byte leak on shutdown, even if it was not cleaned up, would not influence the operation of a Windows machine in any noticeable way between the reboot intervals enforced every 'Patch Tuesday'.
I'm sure you have plenty more bugs with more serious effects to deal with. If not, you can have some of mine!
Rgds,
Martin

Related

C++ - Windows - catch process exit from Task Manager

I need to stop a service when our program has been killed with the task manager.
I tried with std::signal(...) and _onexit(...) but it does not work.
I tried running ProcessMonitor so check a sort of signal I can catch, but I did not find one.
I tried with a:
auto serviceStopThread = QThread::create([](){
::WaitForSingleObject(::GetCurrentProcess(), INFINITE);
ServiceUtils::stopService();
});
serviceStopThread->start();
but it does nothing.
How can I do?
While the process is still alive, find the PID, and open it with OpenProcess. You’ll need at least SYNCHRONIZE permission.
Then wait for the handle to become signaled. For example, you can launch a new thread, and call WaitForSingleObject with INFINITE timeout. The handle becomes signaled as soon as the process quits, regardless on the reason.
React however you like but don’t forget to call CloseHandle when you’re done.
If you only want to react when the process is killed suddenly, send some message to your supervising process when the program exits gracefully, to disable the handling.

Why are threads interrupted even when atexit or ConsoleHandler for SetConsoleCtrlhandler is executed?

I have a multithreaded application under Windows 7.
I need to correctly finish jobs in threads which have an open descriptors, connections and so on when a user presses 'X' in the corner of command line, 'Ctrl+C', shuts down OS and so on.
I've set a handler for SetConsoleHandler which sets appropriate flags for other threads to correctly finish their job. But all of them are interrupted and the y exit with code 0xc000013a. SOmetimes even my handler doesn't have time to set flag.
The same problem remains when I try to do the same operations in atexit handler.
Why are all threads stopped even during interruption handler? How can I avoid this and let all my threads finish their job?
sets appropriate flags for other threads to correctly finish their job
Usually it's not enough. You also must wait the threads to finish (thread.join(), or WaitForMultipleObjects, or something similar).
The problem in my case was that some of child-children thread used timed-waiting on system resources so each of them needed to wake from waiting to join thread. And all of them were stopping consecutively so they required too much time to stop.

How to check boost thread is running and Kill it

In my program, it start a boost thread and keep the handler as a member of the main thread.
When user press the cancel button I need to check the started thread still running and if it is running need tho kill that specific thread. here is the pseudo code.
cheating thread
int i =1;
boost::thread m_uploadThread = boost::thread(uploadFileThread,i);
This is the method use to check if thread is still running, but it is not working
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(2);
if (this->uploadThread.timed_join(timeout)){
//Here it should kill the thread
}
The return value true means the thread is completed before the call times out. And looks like what you want is
if(!this->uploadThread.timed_join(timeout))
For stop your thread you can use:
my_thread.interrupt();
in order this to work you have to set an interruption point at the point you want the thread's function stops when you interrupt.
Note: the interruption by it self don't stop the thread it just set a flag and the when an interruption point is reached the thread is interrupted. If no interruption point is found, the thread don't stop.
You can also handle the interrupted exception boost::thread_interrupted that way you can do things depending on if the thread was interrupted or not.
For instance lets assume the next code is inside a thread function:
try
{
//... some important code here
boost::this_thread.interruption_poit(); // Setting interrutption point.
}
catch(boost::thread_interrupted&)
{
// Now you do what ever you want to do when
// the thread is interrupted.
}

c++ thread alive?

How to?
I tried a WaitingForSingleObject, GetExitCodeThread and etc., but when i kill thread with process explorer nothing happens.
while(true)
{
if(GetThreadId(this->hWatchThread) == 0) // Always return killed thread id!
break;
}
Upd:
When i kill thread, it stop working, but i can't get exit code or zero value from GetThreadId
When a thread is killed forcibly, e.g. from the task manager or from Process Explorer, that does not change the thread ID. The thread handle still exists because your process has not yet closed it. And the thread ID associated with that thread still exists. So GetThreadId will always return a non-zero value.
As for the exit code, you can't get a meaningful value for the exit code because the thread did not exit. It was killed. It never had a chance to set an exit code.
What you must do is use one of the wait functions, e.g. WaitForSingleObject, to wait on your thread handle. If that wait terminates because the thread was killed, then the wait function will return and report a successful wait and the thread exit code will be reported as 0. To the best of my knowledge you cannot discern by means of the Windows API that your thread was killed abnormally.
What you could do is use your own mechanism to indicate that termination was abnormal. Create a flag, owned by the thread, to record that termination was normal. Set the flag to false when the thread starts executing. When the thread terminates normally, set the flag to true. This way you can tell whether or not the thread was terminated abnormally by reading the value of that flag after the thread terminates.
If you want to do something after the thread has exited:
WaitForSingleObject(handle_to_your_thread,INFINITE);
MessageBox(NULL,"Thread has exited","Foo",MB_ICONINFORMATION);

How can I kill a forked process in C++?

I am working on a game, so at one point I had to use fork(), the main thread runs opengl graphics, and the child thread runs the game logic.
Now I have a problem. At some point, the user may press the 'Exit' button inside the game, which is handled by the secondary thread. Also, at some point the user may click the X button to exit the game which is handled by the main (glut) thread. So here is my question: how can I kill the other running thread, and exit?
Right now, if I close the window, the second thread keeps running, and if the second thread finishes, the first one keeps running.
Handling the 'X' button could be done using the atexit function, but I haven't found a (safe) way of killing glutMainLoop().
If you are actually calling fork() (instead of starting a new thread) then you are actually creating another running process. When fork() is called, it returns a process-id to the parent process. That can be passed to kill() to kill the process. Under linux this looks like:
#include <signal.h>
pid_t pid = fork();
if (pid == 0) {
// you are in the child process
} else if (pid > 0) {
// you are in the parent process
...
// send a termination signal
kill(pid, SIGTERM);
} else {
// fork had an error which should be logged...
}
You need to choose what signal to send the process. SIGKILL (9) kills it hard for example.
Please be precise about thread and process as they describe different subjects.
Since you use fork() you are actually dealing with processes. I recommend that you use threads instead, since it is much more memory efficient (since the program needs to be in memory only one time) and easier to handle. Of course you have to deal with critical sections yourself.
Here is a good example for working with threads.
If you insist on using processes and fork() you can still send signals and implement specific signal handlers. I'd also read some articles about IPC (Inter Process Communication) like http://tldp.org/LDP/lpg/node7.html.