How to properly close worker threads created for using IOCP - c++

Here is a code snippet from Network Programming for Microsoft Windows:
...
// Determine how many processors are on the system.
GetSystemInfo(&SystemInfo);
// Create worker threads based on the number of
// processors available on the system. For this
// simple case, we create one worker thread for each
// processor.
for (int i = 0; i < SystemInfo.dwNumberOfProcessors; i++)
{
// Create a server worker thread, and pass the
// completion port to the thread. NOTE: the
// ServerWorkerThread procedure is not defined
// in this listing.
HANDLE ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, CompletionPort, 0, NULL);
// Close the thread handle
CloseHandle(ThreadHandle);
}
...
What I don't understand is why the sample closes the thread handles straightaway. Is it not necessary to store them (for example in a std::vector) so you can terminate all the worker threads later when exiting your program?

It is not necessary. From msdn on CloseHandle:
Closing a thread handle does not terminate the associated thread or
remove the thread object. Closing a process handle does not terminate
the associated process or remove the process object. To remove a
thread object, you must terminate the thread, then close all handles
to the thread. For more information, see Terminating a Thread. To
remove a process object, you must terminate the process, then close
all handles to the process. For more information, see Terminating a
Process.
In practive self contained threads are often created with their handles immediately closed, this allowing resource release when thread exits.

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.

Understanding WaitForSingleObject and WaitForMultipleObject

I have a windows service where I am receiving http requests and launching a process for it which might run more than an hour . I need to get notified in main service when a process ends .And when service is ended i need to terminate all child processes . I understand that if I do waitforsingleobject it will hang on windows service until the process is completed , and no further http requests will be entertained ? I am doing following for now which works but its not correct approach .
if(CreateProcess( TEXT(EXEPATH),
procArguments,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi )
)
{
processHandles[processCount] = pi.hProcess;
processStreams[processCount] = eventId.c_str();
processCount++;
}
On Service stop I am doing this
for(int index=0;index<10;index++){
g_pAppLog->Log("Stop Process for processStreams[%d] %s\n",index,processStreams[index].c_str());
int terminationResult = TerminateProcess(processHandles[index],1);
}
The functions WaitForSingleObjectEx and WaitForMultipleObjectsEx allow you to specify a timeout, so that the function will not hang forever.
You can thus call the function in a loop, checking if the process has really terminated, or it's just a timeout expiration.
Anyway, you should not WaitFor anything, unless you have nothing better to do.
If you have a web server, you should listen to connection and spawn responding processes.
If you just want to check if a process terminated, you can call GetExitCodeProcess.
So, summing up, you might either:
Run a loop that:
accepts a request;
spawns a process;
checks if any of the previously created process terminated (without blocking);
Make a two-thread application, with one thread accepting requests, and the other one calling WaitForMultipleObjectsEx in a loop, and possibly handling children termination.
In your main service, you should create a thread to do that, so the main thread can still be running.. In this thread, you should use WaitforMultipleObjects to wait for all the child process to end, once a process is ended, the corresponding code will be execute.
Please check the MSDN for details
Do the waiting in a different thread than the one that is processing SCM requests. Use CreateEvent() to create a waitable manual-reset event, then have the waiting thread use WaitForMultipleObjects() to wait on both the event and the child process at the same time. WaitForMultipleObjects() will tell you which one is signaled first. When the service is being stopped, signal the event with SetEvent(). When the child process exits, its handle will be signaled. If the event gets signaled first, the waiting thread can call TerminateProcess() on the child process.

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.

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

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.