Reputation: 307
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
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
Upvotes: 2
Views: 4262
Reputation: 151
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.
Upvotes: 2
Reputation: 400274
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.
Upvotes: 8