How to check boost thread is running and Kill it - c++

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.
}

Related

How to stop and destroy thread from main thread (from which is created)

I need to create, run, stop thread and then again same process (reloading some new data and need to refresh and cannot use C++11 standard). I have created and run thread like from mine main thread
pthread_t p;
pthread_create(&p, NULL, calculation, some_pointer_to_object);
How to stop and destroy this thread from main thread ?
(pthread_exit is from current thread).
You need to use pthread_cancel().
The only clean way to do so is this: Set up a flag in the main thread, start the thread, poll the flag in your new thread and finish fast if it's set. Everything else but letting your new thread close itself down cleanly on request opens a boatload of cans of worms, and that's an understatement.

How to join threads created dynamically in c/c++

I have written a C/C++ code which implements socket connection and the main thread is in continuous loop listening at its port. When a connection request comes at this port, I have spawned a thread using pthread calls and offloaded the work on this thread. As such i have 'n' threads getting created dynamically for 'n' incoming requests.
The problem is that, if one thread terminates the main thread also terminates.
I have used pthread_join() but It waits for the thread in the argument to finish.In my case, the new threads are not getting spawned once the call to pthread_join() is made.
pthread_t t;
while(1) //server always to be in listen mode
{
client_len=sizeof(client_sockaddr);
client_sockfd=accept(server_sockfd,(struct sockaddr*)&client_sockaddr,&client_len);
pthread_create(&t,NULL,server_thread,(void*)client_sockfd);
(void)pthread_join(t,NULL);
}
If you don't care about the return value from your threads, and you're not interested in when they complete, then you should detach them with pthread_detach or simply create them in a detached state to begin with:
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
while(1) //server always to be in listen mode
{
client_len=sizeof(client_sockaddr);
client_sockfd=accept(server_sockfd,(struct sockaddr*)&client_sockaddr,&client_len);
pthread_t t;
pthread_create(&t,&thread_attr,server_thread,(void*)client_sockfd);
}
pthread_attr_destroy(&thread_attr);
Add printf("check string\n"); after pthread_join in your code. compile and run it now. You might get some idea about your problem.
You will not meet printf function.
Reason for the behavior is pthread_join will wait for first created thread to finish the job.
so unless and until first thread finish the job new thread will not created. So your code will not accept any new client connection.
So don't use pthred_join inside your while(1) then your problem will be solved.
pthread_join is mostly useful when main process want to wait until thread finishes the job.

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);

A sleep in thread causes memory leak

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

Suspending and resuming threads in c++

My application has to suspend and resume a different process every few *microsec*s.
It works fine only sometimes it feels like it suspends the process for non-uniforms times.
I use the win API: ResumeThread and SuspendThread.
On the other hand, I tried something a little different.
I suspended the thread as usual with SuspendThread but when I resume it, I do like so:
while (ResumeThread(threadHandle) > 0);
and it works faster and it runs the other process in a uniform pace.
Why does it happen? is it possible that sometimes the thread gets suspended twice and then the ResumeThread command executes?
thanks :)
SuspendThread() call does not suspend a thread instantly. It takes several time to save an execution context, so that ResumeThread() might be called when a thread has not suspended yet. That's why while (ResumeThread(threadHandle) > 0); works. To determine the current thread state you can call NtQueryInformationThread(), but only in NT versions of Windows.
If you have a loop in the secondary thread, you can change your synchronization with a Manual Reset Event. The primary thread should call ResetEvent() to suspend a thread, and SetEvent() to resume. The secondary thread every loop should call WaitForSingleObjectEx().
I followed Damon's suggestion, removed suspend / resume from the code and instead used a synchronization object over which my pool thread waits infinitely after completing the work and the same is signaled by my server thread after allocating work to it.
The only time I have to use suspend now is when I create the thread for the first time and after allocating work to it the thread is resumed from my server thread. The thread created is used in a thread pool over and over again to do some work.
It is working like a charm.
Thank you Damon!
Regards,
Ajay
thats the way de loop look's like
for(i=0;i<num;i++) {
while (ResumeThread(threadHandle) > 0);
ResumeThread(threadHandle)
SuspendThread(threadHandle);
}
SuspendThread takes a few milliseconds so the while loop goes on until thread is suspended, after that, again the thread process SuspendThread function is called, a good way to call GetProcessContext to see EIP