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

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.

Related

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

How pthread_join() determine that called/waiting thread is terminated

i am new in Multithreading. in pthread_join() function we put the main thread on wait till the called thread is not terminated. So my question is here how pthread_join() verify that called thread is terminated.
pthread_join is a portable interface around an operating system facility that instructs the OS scheduler to suspend the calling thread until the target thread has communicated that it has completed (either by returning from its entry point function or because pthread_exit has been called). The necessary wrapping logic and state set up by pthread_create. Essentially, you are waiting for a flag to change, but that's all handled for you by the pthreads library.

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

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