Reputation: 461
Consider a multithreaded windows server application. for the sake of generality, let us assume all threads are running the same function:
DWORD WINAPI threaded_function(LPVOID p)
{
while (TRUE) { // do things }
}
Also , lets assume we're keeping references for all these threads. What would be the best practice for a graceful termination? (Keep in mind that as a service , we share a process among an unknown number of services and any kind of process termination methods are out of question)
My best guess would be:
Altering the while (TRUE)
statement , with while(global_event.not_signaled() )
(where global_event
is an instance of a class that wrap the Win32
Event
object and the method called is obvious)
Now, implement the termination function as follow:
global_event.set(); Sleep(/* what would be a reasonable time to wait here? */ ); thread_container.terminate_all();
The restriction we have, is that the application must eventually finish execution of all of it thread, and release all of it's VM and resources among of which are the thread's kernel objects.
Is there any better way to do this? are there any disadvantages in the specified method?
Upvotes: 0
Views: 122
Reputation: 598
You can create a mutex and take it on the caller thread, like:
void caller(){
HANDLE mutex;
CreateMutex(mutex);
WaitForSingleObject(mutex); // take the mutex ownership
createThread(threadedfunction, mutex);
// do things
ReleaseMutex(mutex);
//end
}
And on your threadedfunction wait for the release like:
void threadefunction(HANDLE mutex){
while(WaitForSingleObject(mutex,1)==WAIT_TIMEOUT){
// do things
}
ReleaseMutex(mutex);
}
This way you threadedfunction will keep runing while the mutex can't be taken, the waitforsingleobject will be timing-out with one milisecond wait and do things until it can take the mutex and exit.
Upvotes: 1