hello everyone I have some question about threads if for example I have some thread 1 which allocates some piece of the memory, and anohter thread (let's assume 2) is killing thread 1 using pthread_cancel() or just using return what is going on with the peace of memory which it allocated? will be leak if thread 1 didn't free this piece of memory? thanks in advance for any answer
edited
just to make it clearer, as I know pthread_cancel() kills thread, but what is going on with its memory when I kill it? In case of return all thread will be dead if 1 is the main thread
Yes, it will leak memory in that case. C does not have any garbage collection -- if you allocate memory and fail to free it, it will be leaked, plain and simple.
If you want to avoid leaking memory, don't call pthread_cancel. Make your threads exit gracefully by setting a flag asking them to exit, and then when they detect that that flag is set, they can free their memory and kill themselves by returning from their thread procedures or by calling pthread_exit.
Alternatively, you can set a thread cleanup handler by calling pthread_cleanup_push, which will get called when your thread exits or gets canceled by a call to pthread_cancel. You can use a handler function which will free any allocated memory you have outstanding.
First of all whether it gets cancelled immediately or not depends on cancellation state.
please check "pthread_setcancelstate" and "pthread_setcanceltype".
Also it is important to have a handler after a thread is cancelled.In the handler all the resources must be freed, like locks and memory, it is similar with the return.So, Yes, there is a chance of leak if implementation is not right.
I suggest to look at the implementation of a method or function before using it.
Hope this helps.
Related
I am writing a c terminal program that runs until the user terminates it with Ctrl+C. Think something like ping or top.
My program allocates to the heap but starts no other threads or processes. Should I be handling SIGINT and freeing any allocated memory before exit or is leaving it to the OS better practice?
The short answer is yes given your context, which is a normal exit situation. In an abnormal exit situation, then the short answer is absolutely no.
If you are concerned that your program is leaking memory during its execution, which is a bad thing in the sense that it slows your program execution, then you can keep track of the memory that you allocate and then free it before you exit. Then you can run your program with valgrind and if valgrind complains about blocks that weren't free'd, then you will know you have some type of leak. The location of the allocation will help you know if the leak is of any importance.
If you exit anyway, you don't need to release any resources. The OS will take care of it just fine, and there is no benefit in doing it manually.
Note that free() is not async-safe, so you would definitely have to do the actual freeing in the main thread, and not in the handler. But don't do that, unless you want to do other things than exit().
Use SIGINT handlers for things like resetting the terminal (e.g. with ncurses), or saving critical state.
Tried to search the answer for this question in google , but could not find it.
Consider a case where a thread is killed before it frees the memory that has been allocated at the beginning of the thread execution.
thread_func() {
memory is allocated in the heap using either malloc/calloc
---thread is killed while executing---
Free(memory)
}
How do you free the memory in such cases?
The simple answer is, do not terminate the thread, that is really bad design. In general, this will leave all allocated resources hanging in the free and not released until the process is closed.
Think of a way to redesign the code instead.
As an example, read the Microsoft documentation for all the risks.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx
I experience some memory allocation problems and try to detect possible reasons for these problems.
There are many possible reasons, and lots of hours must be spent to check each of them.
One of the possible reasons is that there is a memory buffer, that is allocated within a thread, and this buffer is used after the thread terminates.
So, if there is a chance that thread termination causes memory deallocation, then many hours of debugging may be avoided.
Thank you very much in advance.
I don't think it does, although it of course might depend on your particular details.
Generally, memory allocation from the operating system's point of view is a per-process activity, while threads exist inside the process. So if one thread allocates memory and then dies, the operating system doesn't clean that up since the process is still alive. Memory is shared inside the process, so the OS can't know that the memory no longer is used and can be cleaned up.
No, threads that 'die' do not deallocate any memory.
When a thread ends, the thread itself vanishes from memory, like a function does once it's done executing. It will take all the 'stack' objects with it, but all the memory you allocated yourself (i.e. malloc) will still be there.
As such, before you end your thread, you should make sure that all dynamic memory that was used by the thread and is not needed any more is freed properly.
Anything on the thread's stack (a local variable, for example) becomes invalid when the thread ends. However, if the data is in the heap, then the memory is still valid as long as the process is running. Of course, you'll need to save the pointer to that heap allocation somewhere outside that thread.
Memory allocated by a thread behaves like memory allocated by a method call:
variables on the stack will be dealocated when the method returns (thread terminates)
variables on the heap will continue to be allocated unless explicitly deallocated.
In addition to all answers, I'd like to make a note that pthread has a TLS keys which are registered with pthread_key_create which accepts key ID and destructor functions. On pthread_exit a static pthread_key_clean_all() is called that iterates through the keys and invokes assigned destructors that may perform memory deallocation (by application design).
So, to understand that - search in your code all pthread_key_create invocations, check if a destructor assigned and the put breakpoints to all of them to check what and in which order is destroyed.
I am writing an API that uses sockets. In the API, I allocate memory for various items. I want to make sure I close the sockets and free the memory in case there is a signal such as Ctrl-C. In researching this, it appears free() is not on the safe function list (man 7 signal) thus, I can't free the memory inside a signal handler. I can close the socket just fine though. Does any have any thoughts on how I can free the memory? Thank you in advance for your time.
Alternatively, don't catch the signal and just let the OS handle the cleanup as it's going to do during process cleanup anyway. You're not releasing any resources that aren't tied directly to the process, so there's no particular need to manually release them.
One technique (others exist too):
Have your program run a main processing loop.
Have your main processing loop check a flag to see if it should "keep running".
Have your signal handler simply set the "keep running" flag to false, but not otherwise terminate the program.
Have your main processing loop do the memory cleanup prior to exiting.
This has the benefit of placing both the allocation and de-allocation in blocks of code which are called with a known sequence. Doing so can be a godsend when dealing with webs of interrelated objects, and there is not going to be race condition between two processing flows trying to mess with the same object.
Don't free in the handler. Instead, indicate to your program that something needs to be freed. Then, detect that in you program, so you can free from the main context, instead of the signal context.
Are you writing a library or an application? If you're writing a library, you have no business installing signal handlers, which would conflict with the calling application. It's the application's business to handle such signals, if it wants to, and then make the appropriate cleanup calls to your library (from outside a signal-handler context).
Of course even if you're writing an application, there's no reason to handle SIGINT to close sockets and free memory. The only reasons to handle the signal are if you don't want to terminate, or if you have unsaved data or shared state (like stuff in shared memory or the filesystem) that needs to be cleaned up before terminating. Freeing memory or closing file descriptors that are used purely by your own process are not tasks you need to perform when exiting.
I have a thread function which allocates memory using malloc(). I kill the thread using pthread_kill without freeing the dynamically allocated memory.Will it be freed automatically once i call pthread_kill or there will be a leak?
Memory you are allocating in one thread doesn't "belong" to that thread. It is allocated from the same global heap all the other threads are using your program. So you have to free all the memory you have allocated otherwise you end up with a leak.
As vicatcu says, there will be a leak.
I wouldn't ever recommending using pthread_kill unless you absolutely have to. Instead, you should create a signaling mechanism to let the thread know when it should be finished, and then join on the thread. And the thread function should poll that value occasionally, and if it gets a terminate signal, it should clean up its own resources and exit.
The other option, of course, is to try not to allocate memory in threads. But I guess you don't always get that luxury. :-)
there will be a leak. how would pthreads kill function possibly know the names of variables that have been assigned via malloc? There is no garbage collection in C, if you call malloc somewhere, you better make sure that you call free somewhere else.
[Edit]
Maybe you should just set a global flag variable associated with your thread, and have your thread poll that variable occasionally to know if and when it should terminate itself.
Yes, assuming you don't install a signal handler for the signal you use and the default action for the signal is process termination.
That's because pthread_kill does not kill a thread, it sends a signal to the thread. If the action of that signal is to terminate the process, then the whole process ceases to exist, and with it, any dynamic memory allocated by any thread in the process.
There is no way to kill a thread.