Suspending and resuming threads in c++ - 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

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.

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

"Sleep" function and suspend count

I want to find out whether or not a certain process is sleeping or not (C++/Windows).
I'm trying to use the suspend count to do so and suspending to process before the check for
profiling processes.
I'm doing something like this:
SuspendThread(threadHandle);
... Do Some Stuff ...
int suspended = ResumeThread(threadHandle);
if (suspended > 1)
m_isSleeping = true;
According to MSDN: http://msdn.microsoft.com/en-us/library/ms685086%28v=vs.85%29.aspx
If a process is suspended, "ResumeThread" returns a value > 0.
In my case, the process is a sleeping process, so I'd expect that the suspend count would be [My Call To SuspendThread] + [The "Sleep" method within the process] = 2
but I keep getting: ResumeThread(threadHandle) == 1
Does anybody know why it happens?
thanks :)
A thread in Sleep isn't suspended, hence the return value of 1
You're confusing threads and processes. ResumeThread and SuspendThread do not operate on process handles, they operate on thread handles. Also, Sleep does not change the suspend count of a process, only ResumeThread and SuspendThread change that. If you're trying to detect if a thread is currently in a Sleep call, you're doing it wrong.
in addition to what others said, your SuspendThread call is not guaranteed to suspend thread immediately, it can be running for a time, and you can actually call ResumeThread while thread is still running (see details: http://www.dcl.hpi.uni-potsdam.de/research/WRK/2009/01/what-does-suspendthread-really-do/)

Windows Threading Wait Method

I'm creating a thread class to encapsulate the windows thread methods. I'm trying to create a method that makes the application wait for the thread to complete before it exits the application. If I use a while loop and boolean flag, it works but obviously it spikes my CPU use and it's just not ideal.
What ways would you use to wait for the completion of a thread? I'm not really looking for code here, just areas to look into.
After you use CreateThread to get a thread handle, pass it into the Win32 API WaitForSingleObject:
WaitForSingleObject(threadhandle, INFINITE);
If you do not use CreateThread (because you use another threading package), or perhaps your thread is always alive...
Then you can still use WaitForSingleObject. Just create an event first with the Win32 API CreateEvent, and wait for the event to be set with WaitForSingleObject. At the end of your thread set the event with SetEvent and you can reset the event with ResetEvent.
Most threading packages though will have their own way to wait for a thread. Like in boost::thread you can use .join() or a boost::condition.