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

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.

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

Do you have to wait for a child thread to finish before you leave the thread that started it?

So lets say you create a thread in main (thread 1). This thread takes in some input from a file and creates multiple other threads (thread 2...etc) to process something. Do you have to exit the other threads (thread 2...) before exiting thread 1? If so how would I go about waiting for all the threads spawned by thread 1 to finish?
There are no parent/child relationships among threads. Threads are all peers. It makes no difference which thread started another thread, all the threads are equal parts of the process that contains them.
The special rule about calling pthread_exit from main only applies because returning from main terminates the process. There is no such concern with other threads -- they could only terminate the process by calling exit or a similar function.
Note that you should either join or detach each thread. You can detach all your threads and then you never have to worry about joining them -- they'll just run to completion and then clean themselves up.
No, you don't have to wait for the other threads to exit, in most situations. The whole point of threads is to start a sub-process of sorts that's largely independent of the thread that started it.
If you don't care how/when the thread will exit, though, you should usually detach the thread. Otherwise, it'll assume you care about its exit status, and it will sit there taking up resources -- even after it exits -- until some other thread joins it to retrieve the exit status.

What does pthread_exit do so that main should call it to prevent other threads from dying prematurely

http://man7.org/linux/man-pages/man3/pthread_exit.3.html
The man page above does not tell why main() should terminate by calling pthread_exit, it only says that it should. Any comments will be appreciated.
The thread that executes main is special, returning from it is equivalent to call exit for the whole process. So this would kill all other threads.
If you just terminate it with pthread_exit the process keeps running until all other threads terminate one way or another.
The other alternative to give the other threads time to do their job would be to join all threads that are created by means of pthread_join.
The function pthread_exit() allows other threads to continue execution, where as exit(3) will terminate every thread.

is it necessary to call pthread_join()

I create more than 100 threads from my main() so I just wanted to know that do I need to call pthread_join() before I exit my main().
Also, I do not need the data generated by these threads, basically, all the threads are doing some job independent from main() and other threads.
pthread_join does two things:
Wait for the thread to finish.
Clean up any resources associated with the thread.
If you exit the process without joining, then (2) will be done for you by the OS (although it won't do thread cancellation cleanup, just nuke the thread from orbit), and (1) will not. So whether you need to call pthread_join depends whether you need (1) to happen.
If you don't need the thread to run, then as everyone else is saying you may as well detach it. A detached thread cannot be joined (so you can't wait on its completion), but its resources are freed automatically if it does complete.
Yes if thread is attachable then pthread_join is must otherwise it creates a Zombie thread.
Agree with answers above, just sharing a note from man page of pthread_join.
NOTES
After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated.
Joining with a thread that has previously been joined results in undefined behavior.
Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when
enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).
When you exit, you do not need to join because all other threads and resources will be automatically cleaned up. This assumes that you actually want all the threads to be killed when main exits.
If you don't need to join with a thread, you can create it as a "detached" thread by using pthread_attr_setdetachstate on the attributes before creating the thread. Detached threads cannot be joined, but they don't need to be joined either.
So,
If you want all threads to complete before the program finishes, joining from the main thread makes this work.
As an alternative, you can create the threads as detached, and return from main after all threads exit, coordinating using a semaphore or mutex+condition variable.
If you don't need all threads to complete, simply return from main. All other threads will be destroyed. You may also create the threads as detached threads, which may reduce resource consumption.
By default threads in pthreads library are created as joinable.
Threads may, however, detach, rendering them no longer joinable. Because threads consume system resources until joined, just as processes consume resources until their parent calls wait(), threads that you do not intend to join must be detached, which is a good programming practice.
Of course once the main routine exits, all threading resources are freed.
If we fail to do that(detaching), then, when the thread terminates it produces the thread equivalent of a zombie process. Aside from wasting system resources, if enough thread zombies accumulate, we won't be able to create additional threads.
Per default a thread runs attached, that means the resources it needs are kept in use until the thread is joined.
As from your description noone but the thread itself needs the thread's resources, so you might create the thread detached or detach the thread prior to having it started.
To detach a thread after its creation call pthread_detach().
Anyhow if you want to make sure all threads are gone before the program ends, you should run the threads attached and join them before leaving the main thread (the program).
If you want to be sure that your thread have actually finished, you want to call pthread_join.
If you don't, then terminating your program will terminate all the unfinished thread abruptly.
That said, your main can wait a sufficiently long time until it exits. But then, how can you be sure that it is suffucient?
If your main ends your application ends and your threads die... So you do need to use thread join (or use fork instead).

Resources