thread at exit cleanup - c

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

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 kill a running thread? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
kill thread in pthread
Here after a source code containing a launch of thread and then after a while I want to kill it. How to do it ? Without make any change in the thread function
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_t test_thread;
void *thread_test_run (void *v) // I must not modify this function
{
int i=1;
while(1)
{
printf("into thread %d\r\n",i);
i++;
sleep(1);
}
return NULL
}
int main()
{
pthread_create(&test_thread, NULL, &thread_test_run, NULL);
sleep (20);
// Kill the thread here. How to do it?
// other function are called here...
return 0;
}
You can use pthread_cancel() to kill a thread:
int pthread_cancel(pthread_t thread);
Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..So you should first use pthread_cleanup_push() to add cleanup functions that will be called when the thread is cancelled. From man pthread_cleanup_push(3):
These functions manipulate the calling thread's stack of
thread-cancellation clean-up handlers. A clean-up handler is a
function that is automatically executed when a thread is cancelled (or
in various other circumstances described below); it might, for
example, unlock a mutex so that it becomes available to other threads
in the process.
Regarding the question of whether a thread will be cancelled if blocking or not, it's not guaranteed, note that the manual also mentions this:
A thread's cancellation type, determined by pthread_setcanceltype(3),
may be either asynchronous or deferred (the default for new
threads). Asynchronous cancelability means that the thread
can be canceled at any time (usually immediately, but the system does
not guarantee this). Deferred cancelability means that cancellation
will be delayed until the thread next calls a function that is a
cancellation point.
So this means that the only guaranteed behaviour is the the thread will be cancelled at a certain point after the call to pthread_cancel().
Note:
If you cannot change the thread code to add the cleanup handlers, then your only other choice is to kill the thread with pthread_kill(), however this is a very bad way to do it for the aforementioned reasons.
The short answer is this: With the cooperation of the code that thread is running, you may terminate it using any method it supports. Without the cooperation of the code that thread is running, you shouldn't even try it. What if the thread is holding a critical lock when you kill it? What if the thread has allocated memory and there is no other code to free that memory?

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.

Detached Threads

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.

Resources