I have a parallel C program running on a shared memory architecture using pthreads. How do I kill a thread without killing the whole process? I.e. if one thread finishes first, I want to wait for all the others before exiting. exit(status_code) kills the whole process which is not what I want. I could have a barrier, wait for all threads to reach the barrier and then exit but there might be an easier way?
Thank you.
Use pthread_join in the "main" (driver) thread to wait for all the other ones to terminate.
To clarify what "a thread terminates" above means, look at the pthread_exit manpage says:
Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function's return value as the thread's exit status.
So pthread_join waits for the joined thread to either return from it start function or call pthread_exit.
(You do need to keep track of all the threads you created to use this. And none of these work if you detached the processing threads - you should probably not be doing that in this case anyway.)
You can use pthread_join() function to join all of your threads.
As an example, lets say you created 5 threads and you want to contunie your operation from main function when all of the threads are finished.
pthread_t threadId[5]; // holder for 5 thread
// Create 5 threads
for(index = 0; index < 5; index++)
pthread_create(&(threadId[index]), NULL, producer, (void *) &(argsForProducers[index]));
// Join them
for (index = 0; index < 5; index++)
pthread_join(threadId[index], NULL);
You can call pthread_exit() to end the thread yo are in. If you want to kill a thread from within another thread, you can call pthread_cancel(threadToKill). To synchronize alll threads you can call pthread_join().
You want to use a join operation for your application to wait on the threads. Take a look at the pthread man page for a good overview.
Related
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.
Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.
Here's the simple program:
void* prisntstr(void* string);
int main(int argc, char *argv[])
{
char* string = "Hello!";
pthread_t thread;
pthread_create(&thread, NULL, prisntstr, (void*)string);
pthread_join(thread, NULL);
}
void* prisntstr(void* string)
{
char* str = (char*)string;
printf("%s\n", str);
}
Does anyone know how I can do this without using pthread_join()?
The problem with your program, if you remove the pthread_join, is that main is returning and thereby causing the program to exit without doing anything to synchronize with the other thread and determine whether it's actually finished. When main returns, it's just as if you called exit, and the whole process terminates.
Aside from pthread_join there are lots of ways you could make main wait for other actions to be finished. You could wait on a semaphore that the other threads post, you could loop on a condition variable inspecting data other threads set, etc.
Alternatively you could have main call pthread_exit so to terminate the initial thread. Then the process will not exit until you call exit or until each thread has exited.
The thread calling pthread_join() just waits for another thread to finish. Please note that:
If that thread has already terminated, then pthread_join() returns immediately
It is the most elegant way for doing it, being the others more complicated, and involving IPC tecniques:
the calling thread could wait for a mutex/semaphore put by the secondary thread
the calling thread could wait for a signal sent by the secondary thread
... and so on
So basically the strategy is: synchronize threads so that
The main thread can obtain some information calculated by the child thread
The process is kept alive until the child thread has completed its action (like in this case)
The reason why without pthread_join() you dont see that message printed to stdout is that as soon as main terminate, it terminates the whole process and all children threads are terminated; in your case before the print is executed.
When you use thread in your program, created thread will became child thread and the main program will became main thread. So, we need to block the main thread so that it can not close.
If main thread closed then child threads will be exit as well.
So, You need to find the way how to block main thread to not exit.
thread gives us the facility for that is pthread_join(). This will block the main thread until the child thread is working. Main thread will block on pthread_join() line. It will not execute other lines.
If you want to not use pthread_join() you need to find other ways for that.
Ex:
while(1);
while(1); will not end the main thread until you kill the process.
All the examples that I have seen about multithreading uses this method in the main method to wait until the thread is done:
pthread_join(thread_id, NULL);
But what if I don't want it to wait? I want my main function to continue as the thread is doing it's work, but at the same time, I don't want main to exit before the thread exists. Is this possible in C/C++?
If you want to avoid using pthread_join(), then pthread_detach() is an option.
From man-page:
int pthread_detach(pthread_t thread);
The pthread_detach() function marks the thread identified by thread
as detached. When a detached thread terminates, its resources are
automatically released back to the system without the need for
another thread to join with the terminated thread.
it does not prevent the thread from being
terminated if the process terminates using exit(3) (or equivalently,
if the main thread returns).
If I called pthread_create() to create a thread, how can I make this thread stay alive even if the main process has exited?
If you detach the thread, the process will not actually end until the last detached thread has finished, however only the detached threads will run.
You can detach a thread using pthread_detach.
For this to work though, you have to exit the main thread (the one running the main function) using pthread_exit and not exit or by returning from it.
It is not possible. Process consists of threads and thread cannot exist by itself.
However, if you meant 'main thread has exited' instead of 'main process has exited', then see the last explanation below in case where main() exits without calling pthread_exit. In this case all the threads are terminated implicitly. If main() called pthread_exit before termination, then only the main thread exits and the other created threads continue to run.
There are several ways in which a thread may be terminated:
The thread returns normally from its starting routine. It's work is done.
The thread makes a call to the pthread_exit subroutine - whether its work is done or not.
The thread is canceled by another thread via the pthread_cancel routine.
The entire process is terminated due to making a call to either the exec() or exit()
If main() finishes first, without calling pthread_exit explicitly itself
It is not possible to have an alive thread after main process has exited. However using pthread_exit(..) instead of exit(..) inside main(..), you can wait for other threads to exit. This will terminate the main thread but other threads will continue to execute.
For more information about pthread_exit(), visit this link.
It is not possible to make thread stay alive even if the main process has exited.
As thread are part of main process and it uses the same resource, once main program got exited
it will also free its resources. So thread can not be alive after process exit.
A thread runs "under" a process. The main() code runs in a thread. Any other threads that you create in main() (or in other threads) run under the same process.
It should be possible to let your main() thread exit WITHOUT waiting to join other threads that are currently running under the same process. However, I mostly use Windows and have NOT tried this running in a *nix system.
If you do this make sure each thread releases its resources prior to exiting.
What you can do is to not exit main(). At the end of your processing in main, right where you would otherwise exit, just put in something like:
int main(void) {
...
...
while (1) sleep(10);
return (0);
}
... or something similar. A process is a container for all the threads spawned within it, and it must exist for the threads to continue to exist. There is no harm in leaving the main() thread alive so that other threads continue to execute.
A thread on itself cannot be made running outside its generating main thread.
It's the definition of thread.
Now, what you can do is to have that thread spawn another process with all the relevant information and then joining back to the main thread before dying.
Anything else I fear will require the main thread to be kept alive.
I'm currently writing a program that the main thread is going to create three child threads. These threads are running simultaneously and what I want to do is once one of the child thread is done, I will check if the output is right. If it is, then terminate the other two threads; if not, then throw away this thread's result and wait for the other two threads' result.
I'm creating the three results in the main function with pthread_create. But I do not know how to use join function. If I use join function three times in the main function, it just waits one by one until the three threads are done.
My plan is like this:
int return_value;
main(){
pthread_create(&pid[0], NULL, fun0, NULL);
pthread_create(&pid[1], NULL, fun1, NULL);
pthread_create(&pid[2], NULL, fun2, NULL);
}
fun0(){
...
if( check the result is right ){
return_value = result;
if (pid[1] is running) pthread_kill( pid[1], SIGTERM );
if (pid[2] is running) pthread_kill( pid[2], SIGTERM );
}
fun1() ...
fun2() ...
function 0, 1, and 2 are similar to each other and once one function has the right answer, it will kill the other two threads. However, while running the program, once the pthread_kill is processed, the whole program is terminated, not just one thread. I don't know why.
And I still do not know if there are any other ways to code this program. Thanks for helping me out of this.
The pthread_kill() function is not designed to terminate threads, just like kill() is not designed to terminate processes. These functions just send signals, and their names are unfortunate byproducts of history. Certain signal handlers will cause the process to terminate. Using pthread_kill() allows you to select which thread handles a signal, but the signal handler will still do the exact same thing (e.g., terminate the process).
To terminate a thread, use pthread_cancel(). This will normally terminate the thread at the next cancellation point. Cancellation points are listed in the man page for pthread_cancel(), only certain functions like write(), sleep(), pthread_testcancel() are cancellation points.
However, if you set the cancelability type of the thread (with pthread_setcanceltype()) to PTHREAD_CANCEL_ASYNCHRONOUS, you can cancel the thread at any time. This can be DANGEROUS and you must be very careful. For example, if you cancel a thread in the middle of a malloc() call, you will get all sorts of nasty problems later on.
You will probably find it much easier to either test a shared variable every now and then, or perhaps even to use different processes which you can then just kill() if you don't need them any more. Canceling a thread is tricky.
Summary
Easiest option is to just test a variable in each thread to see if it should be canceled.
If this doesn't work, my next recommendation is to use fork() instead of pthread_create(), after which you can use kill().
If you want to play with fire, use asynchronous pthread_cancel(). This will probably explode in your face. You will have to spend hours of your precious time hunting bugs and trying to figure out how to do cleanup correctly. You will lose sleep and your cat will die from neglect.
I have an application in which I have 1 main thread which creates 10 different threads for doing some job. At the end of application, when I try to exit, the application is not able to cleanly exit. The stack trace is not that useful, but its showing the crash in function "cancel_deliver()" My first guess is this is some underlying call made while doing the freeing up of resources used by each thread, but not entirely sure.
fyi: The callback function for each thread has a while (1) loop:
Here is the snippet
void main (...)
{
pthread_t tid;
for (int i=0; i<10; i++)
pthread_create(&tid, NULL, xyzCallback, NULL);
}
void xyzCallback(void* data)
{
while (1)
{
////
}
}
void atExit()
{
exit(1);
}
Is there any thing that I can do to free up resrouces used by my thread and cleanly exit?
For this case
If I understand your setup correctly...
One thing you could do is have a set of 'flag' variables, one for each thread (including the main thread). When the main thread is ready to end, set its flag. This flag should be continually checked within the 10 other threads. Once it becomes set, change the flag variable for that specific thread and call pthread_exit. In the main exit method, only terminate once all the flag variables are set.
Assuming your program isn't crashing due to another reason, this should enable all the threads to finish in a controlled manner.
(or use pthread_join in the main exit function, since pthread_exit returns information used by pthread_join)
In general
Use pthread_exit instead of exit(1) to cleanly exit the thread.
From the LLNL POSIX Thread Programming page:
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
Also see the pthread_exit man page.
You need to decide whether your threads (1) need to end in a well defined way (state), or if the latter does not matter (2) take care where and when they could be cancelled (which happens implicitly when the program ends)
Referring 1: A possible way could be to implement an exit condition which will be triggered when the program shall terminate and makes the threads leave their while(1) loop. Before leaving the main loop calling pthread_join() for any pthread_t pthread it received by the calls to pthread_create(). If all threads terminate the main's join loops is left and main ends with all threads terminated already.
Referring 2: This is the more critical case, as depending on the thread functions's code it is not clear where it will be canceled, which could lead to unexpected behaviour. A thread could be cancelled at a so called cancellation point. Some system calls are treated as such.
In any case the thread function does not necessarily need to call pthread_exit() as last statement. This is only necessary if you want to have pthread_join() receive a pointer passed to pthread_exit().