Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread clean up handler

I have some dynamic allocations which I want to make sure are freed when the thread exits/terminates.

Please consider the following scenario:

static void thread_cleanup_handler(void* arg)
{
    free(arg);
}

static void* threadFunction(void* arg)
{
    pthread_cleanup_push(thread_cleanup_handler, arg);
    //do some work with arg...
    pthread_cleanup_pop(1);
    return NULL;
}

something* data = (something*)malloc(sizeof(something));
pthread_create(&id, &attr, threadFunction, (void*)data); //thread is created detached

Question is, if the created thread is cancelled (using pthread_cancel) before it actually started running (it has only been scheduled and has not been executed yet), will the cleanup handler be invoked or is this a potential memory leak?

Please not that the thread is created with PTHREAD_CREATE_DETACHED.

like image 452
Tsef Avatar asked Dec 06 '25 16:12

Tsef


1 Answers

From the POSIX reference for pthread_cancel:

When the cancellation is acted on, the cancellation cleanup handlers for thread shall be called.

So if the thread is canceled any installed cleanup handlers will be run. The problem with your code is that if the thread function haven't yet called pthread_cleanup_push then there are no cleanup handlers to run. Leading, as you suspect, to a leak.

like image 71
Some programmer dude Avatar answered Dec 08 '25 08:12

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!