pthread_detach question - c

Till recently, I was under the impression that if you "detach" a thread after spawning it, the thread lives even after the "main" thread terminates.
But a little experiment (listed below) goes contrary to my belief. I expected the detached thread to keep printing "Speaking from the detached thread" even after main terminated, but this does not seem to be happening. The application apparently terminates...
Do the "detached" threads die after "main" issues return 0?
#include <pthread.h>
#include <stdio.h>
void *func(void *data)
{
while (1)
{
printf("Speaking from the detached thread...\n");
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
pthread_t handle;
if (!pthread_create(&handle, NULL, func, NULL))
{
printf("Thread create successfully !!!\n");
if ( ! pthread_detach(handle) )
printf("Thread detached successfully !!!\n");
}
sleep(5);
printf("Main thread dying...\n");
return 0;
}

To quote the Linux Programmer's Manual:
The detached attribute merely
determines the behavior of the system
when the thread terminates; it does
not prevent the thread from being
terminated if the process terminates
using exit(3) (or equivalently, if the
main thread returns).
Also from the Linux Programmer's Manual:
To allow other threads to continue
execution, the main thread should
terminate by calling pthread_exit()
rather than exit(3).

pthread_detach just means that you are never going to join with the thread again. This allows the pthread library to know whether it can immediately dispose of the thread resources once the thread exits (the detached case) or whether it must keep them around because you may later call pthread_join on the thread.
Once main returns (or exits) the OS will reap all your threads and destroy your process.

pthread_detach does not do what you think it does - it indicates to the implementation that the space the thread with the specified ID is using can be reclaimed as soon as it terminates, ie. no pthread_join operation will be performed on it.
All threads are terminated once the process containing them is terminated.

Yes, the detached threads will die after return 0.
From the NOTES section of man pthread_detach
The detached attribute merely
determines the behavior of the system
when the thread terminates; it does
not prevent the thread from being
terminated if the process terminates
using exit(3) (or equiv‐alently, if
the main thread returns)

From man pthread_detach:
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.

Related

How to make pthreads work concurrent without pthread_join()

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.

Multithreading in C/C++ without waiting for the thread to finish

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

How to keep a thread alive after the main process exited?

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.

thread at exit cleanup

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().

Detached vs. Joinable POSIX threads

I've been using the pthread library for creating & joining threads in C.
When should I create a thread as detached, right from the outset? Does it offer any performance advantage vs. a joinable thread?
Is it legal to not do a pthread_join() on a joinable (by default) thread? Or should such a thread always use the detach() function before pthread_exit()ing?
Create a detached thread when you know you won't want to wait for it with pthread_join(). The only performance benefit is that when a detached thread terminates, its resources can be released immediately instead of having to wait for the thread to be joined before the resources can be released.
It is 'legal' not to join a joinable thread; but it is not usually advisable because (as previously noted) the resources won't be released until the thread is joined, so they'll remain tied up indefinitely (until the program exits) if you don't join it.
When should I create a thread as detached, right from the outset?
Whenever the application doesn't care when that thread completes and doesn't care about its return value of a thread, either (a thread may communicate a value back to other thread/application via pthread_exit).
For example, in a client-server application model, a server may create a new thread to process each request. But the server itself doesn't care about thread's return value of the thread. In that case, it makes sense to created detached threads.
The only thing the server needs to ensure is that the currently processed requests are completed. Which it can do so, just by exiting the main thread without exiting the whole program/application. When the last thread in the process exits, the application/program will naturally exit.
The pseudocode might look like:
/* A server application */
void process(void *arg)
{
/* Detach self. */
pthread_detach(pthread_self());
/* process a client request. */
pthread_exit(NULL);
}
int main(void)
{
while (not_done) {
pthread_t t_id;
errno = pthread_create(&t_id, NULL, process, NULL);
if (errno) perror("pthread_create:");
}
/* There may be pending requests at this point. */
/* Just exit the main thread - not the whole program - so that remaining
requests that may still be processed can continue. */
pthread_exit(NULL);
}
Another example could be a daemon or logger thread that logs some information at regular intervals for as long as the application runs.
Does it offer any performance advantage vs. a joinable thread?
Performance-wise, there's no difference between joinable threads vs detached threads. The only difference is that with detached threads, its resources (such as thread stack and any associated heap memory, and so on - exactly what constitutes those "resources" are implementation-specific).
Is it legal to not do a pthread_join() on a joinable (by default) thread?
Yes, it's legal to not join with a thread. pthread_join is a just convenience function that's by no means needs to be used unless you need. But note that the threads created are joinable threads by default.
An example when you might want to join is when threads do a "piece" of work that's split between them. In that case, you'd want to check all threads complete before proceeding. Task farm parallelism is a good example.
Or should such a thread always use the detach() function before pthread_exit()ing?
Not necessary. But you'd often want to decide whether you want a joinable or detached thread at the time of creation.
Note that while a detachable thread can be created in by setting the attribute PTHREAD_CREATE_DETACHED with a call to pthread_attr_setdetachstate, a thread decide can decide to detach itself at any point in time e.g. with pthread_detach(pthread_self()). Also, a thread that has the thread id (pthread_t) of another thread can detach with pthread_detach(thread_id);.

Resources