When we make Detached threads in main.
and supose main exits... do the detached threads keep on going on or do they also exit just like our normal Joinable threads?
It depends entirely on how the main thread exits. If it exits using exit() or returning from main(), then the entire process is exited, and every thread is terminated.
However, if it uses pthread_exit() to terminate, then the process continues running.
If this would be another thread then main, the other threads would continue. But the C99 standard says
If the return type of the main
function is a type compatible with
int, a return from the initial call to
the main function is equivalent to
calling the exit function...
(All common platforms nowadays will return an int from main, in particular this is required by POSIX.)
And the POSIX page for exit states
These functions shall terminate the
calling process...
So in summary a return from main terminates the whole program including all threads.
Related
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 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().
What's the difference between pthread_exit() and exit()?
Did you read man pages?
exit() performs normal program termination, while pthread_exit() kills calling thread.
pthread_exit terminates a thread. Per the docs
Thread termination does not release any application visible process
resources, including, but not limited to, mutexes and file
descriptors, nor does it perform any process level cleanup actions,
including, but not limited to, calling any atexit() routines that may
exist.
exit, on the other hand, does do this.
the differences:
pthread_exit(): terminate a thread-whether its work is done or not
exit() perfoms normal program termination for the entire process.
Threads are created using pthread_create(). Each thread can then independently
terminate using pthread_exit(). (If any thread calls exit(), then all threads immediately terminate.) Unless a thread has been marked as detached (e.g., via a call to
pthread_detach()), it must be joined by another thread using pthread_join(), which
returns the termination status of the joined thread.
I have two threads, communicating with each other; each thread employs 'while(1) ..'. Now I need to let the threads exit upon a specific condition met, and therefore finish the application.
My question: is it safe to just 'return (NULL)' from the thread, or do I have to use 'pthread_exit' or 'pthread_join' functions as well?
It is safe to return null from the thread functions; the code that waits for them should be OK.
POSIX says of pthread_exit():
An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it.
You do need something to wait for the thread with pthread_join() unless the thread was created with the detached attribute or detached later with pthread_detach().
Calling pthread_exit(NULL) and returning NULL at the end of the thread's initial function should be equivalent. However, doing either of these alone will lead to a resource leak. To avoid that, you must either call pthread_join on the thread from another thread, or put the thread in the detached state by calling pthread_detach on it or setting it to start in the detached state before creating it.