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

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

Related

Do you have to close the thread once it has ended when using pthreads in Linux?

In WinAPI, if you create a thread and this thread is then ended, you still have to call CloseHandle() on the thread handle.
When using pthreads in Linux, do you also have to close the thread after it has ended?
The equivalent in pthreads is to call pthread_join() on the thread (this will block until the thread exits, if it hasn't already).
You also have the option to detach the thread with pthread_detach() (or create it detached using the attr argument to pthread_create() with pthread_attr_setdetachstate()), which means the thread no longer needs to be joined.

Can I close/terminate an running thread from its thread function?

I have created a thread, with a custom thread function. I have a condition in the thread function that if it becomes true, I want to close the thread from inside the thread function.
Is it possible?
You can return from the thread and if you want to return some value, you can use pthread_join on that thread.
I assume you are using pthread for the thread functionlaity. You can call the pthread_detach() function in your custom thread function after creating the thread. In the created thread just returning from the thread function will be sufficient to close the thread and release all the resources associated with the thread.
For PThreads there are two ways to end a thread cleanly.
Detached the thread using pthread_detach(). To end it then call pthread_exit(). To find a thread's phtread-id from inside the thread itself use phtread_self().
Call pthread_exit() and have another thread call pthread_join() on the pthread-id received when creating the thread that ended.
If you miss to call pthread_join() on a thread not having been detached by calling pthread_detach(), the resources in use by the thread will not be released, even after the thread ended.
This could lead to a shortage on memory and/or other system resources. Take care this does not happen.
A third was to end a thread is to just cancel it using pthread_cancel(), which typically isn't initated by the thread itself (as I could just use one of the two ways described above to end itself), but from another thread in the situation where the thread to end is not aware of this and could not be notified to do so.
The need to cancel a thread should rarely arise, and if it does one might start to overthink the program's design.

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.

pthread_detach question

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.

POSIX threads and exiting from a 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.

Resources