Kill a running thread - c++

What happens if we forcefully kill a running thread
I have a thread namely RecordThread() which calls some complex and time consuming functions. In these functions I am using try-catch blocks, allocating and deallocation memory and using critical section variables etc.
like
void RecordThread()
{
AddRecord();
FindRecord();
DeleteRecord();
// ...
ExitThread(0);
}
After creating this thread, I am immediately killing it before the thread completes its execution. In this case what happens if the thread is forcefully killed? Do the internal functions (AddRecord, DeleteRecord) complete their execution after we killed the thread?

After creating this thread, I am immediately killing it before the thread completes its execution.
I assume you mean you are using TerminateThread() in the following fashion:
HANDLE thread = CreateThread(...);
// ...
// short pause or other action?
// ...
TerminateThread(thread, 0); // Dangerous source of errors!
CloseHandle(thread);
If that is the case, then no, the thread executing RecordThread() will be stopped exactly where it is at the time that the other thread calls TerminateThread(). As per the notes in the TerminateThread() documentation, this exact point is somewhat random and depends on complex timing issues which are out of your control. This implies that you can't handle proper cleanup inside a thread and thus, you should rarely, if ever, kill a thread.
The proper way to request the thread to finish is by using WaitForSingleObject() like so:
HANDLE thread = CreateThread(...);
// ...
// some other action?
// ...
// you can pass a short timeout instead and kill the thread if it hasn't
// completed when the timeout expires.
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682659%28v=vs.85%29.aspx
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.
However the function calls will of course be completed because they're called before the ExitThread().

killing thread is the last resort - as Andre stated it leaves data in unknown state, you should never do that if thread works on shared object. Better choices are to notify thread to finish work by:
-using global volatile (important) variable which is changed only by main thread and tested by workers
-using signal type synchronization objects (mainly Events) also set by main thread and tested by workers

example of Thread that works well:
definition in *.h ------------------------------------
DWORD WINAPI Th_EspectroIF(LPVOID lpData);
CThread th_espectro(Th_EspectroIF);
use in *.cc -----------------------------------
DWORD WINAPI Th_EspectroIF(LPVOID lpData)
{
//Your code...
th_espectro.Stop(true);//stop this Thread
}
call the Thread with: th_espectro.Start();

Related

How to safely close a THREAD which has a infinite loop in it

I am creating a thread using _beginthreadex function. The function address I am passing in it has an infinite while loop (while(1)) . I have the threadid and threadhandle.
I can use TerminateThread(threadhandle,1); But it is dangerous.
The safe way is to kill thread using _endthreadex but it can only be used from inside the thread, and I wanted to kill the thread from outside.
So please suggest if there is a safe way to close,end or kill the thread safely from outside using threadid or threadhandle.
You should - literally - never use TerminateThread(). And I'm not even joking. If you are terminating a thread from the outside, all resources reserved in it will be leaked, all state variables accessed inside will have an undetermined state and so on.
The solution for your problem might be signaling your thread to finish itself. It can be done by a volatile variable changed by thread-safe means (see InterlockedIncrement() on that), a Windows event, or something like that. If your thread has a message loop you can even do it by sending a message to ask it to stop.
The proper way is to create an event "kill me", by using CreateEvent, then flag this event when you wish to kill the thread. Instead of having your thread wait while(1), have it wait while(WaitForSingleObject(hevent_killme, 0)). And then you can simply let the thread callback finish and return, no need to call _endthreadex or such.
Example of callback function:
static DWORD WINAPI thread_callback (LPVOID param)
{
...
while(WaitForSingleObject(hevent_killme, 0) != WAIT_OBJECT_0)
{
// do stuff
}
return 0;
}
Caller:
HANDLE hevent_killme = CreateEvent(...);
...
void killthread (void)
{
SetEvent(hevent_killme);
WaitForSingleObject(hthread_the_thread, INFINITE);
CloseHandle(hevent_killme);
CloseHandle(hthread_the_thread);
}
Never use TerminateThread.
Instead of while(1), you can use while(continue_running), where continue_running is True when the thread loop should run. When you want to stop the thread, make the controlling thread set continue_running to False. Of course make sure that you properly guard continue_running with mutexes as it is a variable whose value can be modified from two threads.

Thread coordination with WaitForSingleObject and CEvent in MFC

In one of my MFC applications there are several worker threads. Nature of these threads are as below:
Most of the threads execute their tasks once and wait for a condition to be true for further execution.
In few cases thread waits infinitely until the condition becomes true and in other cases it waits for certain time periods and based on the condition becomes true or expiry of the time period whichever is earlier, it takes some action and again starts waiting.
Threads have to run throughout the life cycle of the application but not necessarily working every moment.
Currently each thread is having an infinite loop, where it executes it's task; as each thread has to work throughout the application's life cycle, I don't want to close these threads every time and recreate. Inside the loop I have used WaitForSingleObject with an auto-reset CEvent for such thread coordination. CEvent objects are signaled from any thread or from UI thread.
In this context I have following queries:
i. Is the approach well justified for my requirement?
ii. Is there any significant overhead of using so many CEvent objects for the purpose.
Is there any better alternative?
iii. In some cases a thread waits infinitely for a CEvent object to be signalled and the object is only signalled from windows message handler after it receives a Message from another thread.The message is received through PostMessage. Here I'm concerned about loosing a message sent from a thread. If Message handler skips a message, it cannot state of the CEvent object and the waiting thread has to wait infinitely. What precautions have to be taken to avoid such situation ? Is there any better way to reconstruct the scheme ?
Please suggest me some better alternatives.
Your approach is fine. Don't worry about multiple CEvent objects. In your case you must have at least one event per thread.
I am not sure what method you use to exit the thread. But you may need additional CEvent object to detect whether you have to exit the thread gracefully.
So in this case you would use WaitForMultipleObjects in each thread (1 event would be to run or not, another event would be to exit the thread or not).
If there are too many threads, that I would suggest that you spawn child threads when ever required. The child thread would simply run once and exit. In the parent thread you would again wait to see which child thread must be run. You can detect which thread to spawn based on array of event objects. This approach will take up less system resources.
Use WaitForMultipleObjects instead of WaitForSingleObject. The first event in each event array should be a global CEvent that is set to shutdown the app. Each thread detects this event and exits cleanly by returning from the thread function.
After setting the shutdown event (typically in OnClose) use WaitForMultipleObjects on the thread handles to wait for all the secondary threads to close. This makes sure that any global data that the threads may be accessing remains allocated until the threads are gone.
In my application I'm using 10 to 12 worker threads only. I read somewhere that
when a thread calls a wait function, it enters into kernel mode from the user mode. It is bit costly because to enter the kernel mode, approximately 1000 processor cycles are required which may be too expensive in a concrete situation.
However, as goths and ScottMcP suggested, I'm using WaitForMultipleObjects instead of WaitForSingleObject in the following way to ensure graceful thread closure before cleaning up any resources used by the thread.
CEvent doWork,exitThread; //Auto reset events
CWinThread* MyThread;
UINT MyThreadFunction(LPVOID param);
BOOL CMyDlg::OnInitDialog()
{
//Other initialization code
MyThread=AfxBeginThread(MyThreadFunction, CMyDlg::GetSafeHwnd());
//Any other initialization code
return TRUE;
}
UINT MyThreadFunction(LPVOID param)
{
HANDLE waitEvents[2];
waitEvents[0]=doWork;
waitEvents[1]=exitThread;
while(true)
{
DWORD stat=::WaitForMultipleObjects(2, waitEvents, FALSE, INFINITE);
switch(stat)
{
case WAIT_OBJECT_0 + 0:
// doWork CEvent is signalled; proceed to do some work
break;
case WAIT_OBJECT_0 + 1:
//exitThread is signalled; so exit from this thread handler function
return 0;
case WAIT_FAILED:
// failure may be related to wrong handles passed for lpHandles
break;
case WAIT_TIMEOUT:
// not applicable here because dwMilliseconds parameter is set to INFINITE
break;
}
}
return 0;
}
CMyDlg::OnClose()
{
exitThread.SetEvent();
DWORD Stat=WaitForSingleObject(MyThread->m_hThread, INFINITE);
if(Stat==WAIT_OBJECT_0)
{
//Thread supposed to be Exited
//Cleanup allocated resources here
}
else if(Stat==WAIT_TIMEOUT)
{
//not applicable here
}
else if(Stat==WAIT_FAILED)
{
//Invalid thred handle passed or something else
}
EndDialog(0);
}
Please, do comment on my answer if anything wrong is detected or there is any scope of improvement.

Does QThread::quit() immediately end the thread or does it wait until returning to the event loop?

There are a lot of Qt multi-threading tutorials out there that state that a QThread can be stopped safely using the following two lines.
qthread.quit(); // Cause the thread to cease.
qthread.wait(); // Wait until the thread actually stops to synchronize.
I have a lot of code doing this, and in most cases of stopping thread, I'll always set my own cancel flag and check it often during execution (as is the norm). Until now, I was thinking that calling quit would perhaps cause the thread to simply no longer execute any waiting signals (e.g. signals that are queued will no longer have their slots called) but still wait on the currently executing slot to finish.
But I'm wondering if I was right or if quit() actually stops the execution of the thread where it's at, for instance if something is unfinished, like a file descriptor hasn't been closed, it definitely should be, even though in most cases my worker objects will clean up those resources, I'd feel better if I knew exactly how quit works.
I'm asking this because QThread::quit() documentation says that it's "equivalent to calling QThread::exit(0)". I believe this means that the thread would immediately stop where it's at. But what would happen to the stackframe that quit was called in?
QThread::quit does nothing if the thread does not have an event loop or some code in the thread is blocking the event loop. So it will not necessarily stop the thread.
So QThread::quit tells the thread's event loop to exit. After calling it the thread will get finished as soon as the control returns to the event loop of the thread.
You will have to add some kind of abort flag if you are blocking event loop for example by working in a loop. This can be done by a boolean member variable that is public or at least has a public setter method. Then you can tell the thread to exit ASAP from outside (e.g. from your main thread) by setting the abort flag. Of course this will require your thread code to check the abort flag at regular intervals.
You may also force a thread to terminate right now via QThread::terminate(), but this is a very bad practice, because it may terminate the thread at an undefined position in its code, which means you may end up with resources never getting freed up and other nasty stuff. So use this only if you really can't get around it. From its documentation:
Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
I think this is a good way to finish a thread when you are using loops in a thread:
myThread->m_abort = true; //Tell the thread to abort
if(!myThread->wait(5000)) //Wait until it actually has terminated (max. 5 sec)
{
myThread->terminate(); //Thread didn't exit in time, probably deadlocked, terminate it!
myThread->wait(); //We have to wait again here!
}
In case, if you want to use Qt's builtin facility then try QThread::requestInterruption().
Main thread
struct X {
QThread m_Thread;
void Quit ()
{
m_Thread.quit();
m_Thread.requestInterruption();
}
};
Some Thread referred by X::m_Thread
while(<condition>) {
if(QThread::currentThread()->isInterruptionRequested())
return;
...
}
As per the documentation:
void QThread::requestInterruption()
Request the interruption of the thread. That request is advisory and it is up to code running on the thread to decide if and how it should act upon such request. This function does not stop any event loop running on the thread and does not terminate it in any way.

What is the use of QThread.wait() function?

I have stumbled upon this problem, as others haves:
QThread won't stop / does not process a signal
QThread - Using a slot quit() to exit the thread
The problem is that I want to have a worker thread started, do some job (which involves sending signals to other threads in my code, and receiving signals asynchronously) and then exit. But I want this thread to be synchronized with the code that is starting it. In other words, I want the execution in the code which creates the worker thread to be halted until the worker thread is done its job.
But it seems this is not possible in Qt. The reason is that the worker's QThread.quit() slot cannot be signaled from within the thread itself. The event loop which listens for signals to this slot, should reside in the same thread that created the worker thread. This means the creating thread should not be blocked, otherwise the worker thread never stops.
Which brings me to my question, that what is the point of QThread.wait() then? I think this function should just be stuck at the end of the program to make sure all the threads have exited, but it cannot actually be used to synchronize threads, at least it cannot be used to synchronize a worker thread, with the thread that created it. Because if the QThread.wait() is called from the creating thread, it blocks its event loop, which will block the worker thread's interface, which will prevent it from ever exiting.
Am I missing something?
I thought I need to add a code snippet:
for (auto i = myVector.begin(); i < myVector.end(); ++i)
{
// 5-line best practice creation for the thread
QThread* workerThread = new QThread;
MyWorkerObject* workerObject = new MyWorkerObject(0);
workerObject->moveToThread(workerThread);
QObject::connect(workerThread, SIGNAL(started()), workerObject, SLOT(init()));
QObject::connect(workerThread, SIGNAL(finished()), workerObject, SLOT(deleteLater()));
// Stop mechanism
QObject::connect(workerObject, SIGNAL(finished()), workerThread, SLOT(quit()));
// Start mechanism
wokerThread->start();
// Invoking the work
QMetaObject::invokeMethod(workerObject, "StartYourJob", Qt::QueuedConnection, Q_ARG(SomeType, *i));
// Synchronization
workerThread->wait();
delete wokerThread;
}
I finally found my answer here:
http://comments.gmane.org/gmane.comp.lib.qt.user/6090
In short, if QThread::quit() is invoked as a slot, the event loop handler of the creating thread will deal with it, which is not what I want.
I should call it directly. So when the workerObject finishes its job, instead of sending a signal (which has to pass through the blocked creating thread), it should directly call its container's quit:
this->thread()->quit();
This would be the exit point of the workerObject. Now there is no need for the stop mechanism and these lines can be eliminated from the code.
// Stop mechanism
QObject::connect(workerObject, SIGNAL(finished()), workerThread, SLOT(quit()));
Does anybody see any problem with this approach?
The purpose of threads is to allow processes to run concurrently (at the same time!), so if you're just creating a thread to do work and waiting on the current thread, you don't need to be using a new thread.
To answer your question of the purpose of QThread::wait(), the Qt documentation states that it is similar to the POSIX function pthread_join. A quick search on pthread_join reveals this link, which states the rationale is as follows: -
The pthread_join() function is a convenience that has proven useful in
multi-threaded applications. It is true that a programmer could
simulate this function if it were not provided by passing extra state
as part of the argument to the start_routine(). The terminating thread
would set a flag to indicate termination and broadcast a condition
that is part of that state; a joining thread would wait on that
condition variable. While such a technique would allow a thread to
wait on more complex conditions (for example, waiting for multiple
threads to terminate), waiting on individual thread termination is
considered widely useful. Also, including the pthread_join() function
in no way precludes a programmer from coding such complex waits. Thus,
while not a primitive, including pthread_join() in this volume of
POSIX.1-2008 was considered valuable.
The pthread_join() function provides a simple mechanism allowing an
application to wait for a thread to terminate. After the thread
terminates, the application may then choose to clean up resources that
were used by the thread. For instance, after pthread_join() returns,
any application-provided stack storage could be reclaimed.
The pthread_join() or pthread_detach() function should eventually be
called for every thread that is created with the detachstate attribute
set to PTHREAD_CREATE_JOINABLE so that storage associated with the
thread may be reclaimed.
The interaction between pthread_join() and cancellation is
well-defined for the following reasons:
The pthread_join() function, like all other non-async-cancel-safe
functions, can only be called with deferred cancelability type.
Cancellation cannot occur in the disabled cancelability state.
Thus, only the default cancelability state need be considered. As
specified, either the pthread_join() call is canceled, or it succeeds,
but not both. The difference is obvious to the application, since
either a cancellation handler is run or pthread_join() returns. There
are no race conditions since pthread_join() was called in the deferred
cancelability state.
If an implementation detects that the value specified by the thread
argument to pthread_join() does not refer to a joinable thread, it is
recommended that the function should fail and report an [EINVAL]
error.
If an implementation detects that the value specified by the thread
argument to pthread_join() refers to the calling thread, it is
recommended that the function should fail and report an [EDEADLK]
error.
If an implementation detects use of a thread ID after the end of its
lifetime, it is recommended that the function should fail and report
an [ESRCH] error.
QThread::wait() is not what you need. This function is exactly what you mentioned, it waits for thread termination.
bool QThread::wait ( unsigned long time = ULONG_MAX )
Blocks the thread until either of these conditions is met:
The thread associated with this QThread object has finished execution (i.e. when it
returns from run()). This function will return true if the thread has finished. It also
returns true if the thread has not been started yet.
time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will
never timeout (the thread must return from run()). This function will return false if the
wait timed out.
If you need to synchronize two threads (Your main thread and created thread) then I recommend using signals and slots to signal which one is ready (trigger a isReady bool) and have a while (!isReady) { sleep(1ms); processEvents(); } loop going. May not be the best way but should work.

How can the thread be closed (pthread library)?

I have some code, roughly:
pthread_create(thread_timeout, NULL, handleTimeOut, NULL);
void handleTimeOut()
{
/*...*/
pthread_cancel(thread_timeout);
/*...*/
}
But as I noticed by pthread's manual the cancellation must be used by another threads. I have tried to use pthread_exit() function instead, but this thread hangs on again...
How must the tread termination be handled correctly? Will it be terminated successfully if the function handleTimeOut() just ends without special pthread functions?
Killing a thread without its cooperation is a recipe for problems. The right solution will be one that allows an external thread to request the thread to clean up and terminate, and has the thread periodically example this state and when it's been requested, it follows through with the request. Such a request can be done through anything that all threads can share.
If a thread wants to finish, it can either call pthread_exit() or it can return from the initial thread function. These are equivalent.
I don't see any reason why a thread couldn't call pthread_cancel() on itself, but this would be highly unusual.