3

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.

Tsef
  • 1,018
  • 9
  • 22

2 Answers2

2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • that's what I was afraid of, any possible solutions/suggestions? – Tsef Feb 01 '18 at 10:56
  • 1
    @Tsef I *think* you don't actually have to worry about it. Calling `pthread_cancel` doesn't actually cancel the thread immediately. Instead the thread have to reach a *cancelation point*, and with your example I don't think there's a cancelation point before the "call" to `pthread_cleanup_push`. Therefore you will never have a leak, since the cleanup handler will have been registered before the first possible cancelation point. – Some programmer dude Feb 01 '18 at 11:18
  • 2
    Some more related info here if anyone needs (the thread must necessarily run to be cancelled): https://stackoverflow.com/questions/17719933/when-is-posix-thread-cancellation-not-immediate – Tsef Feb 01 '18 at 13:05
0

By default, there is no leak.

POSIX.1 specifies that certain functions must, and certain other functions may, be cancellation points. If a thread is cancelable...then the thread is canceled when it calls a function that is a cancellation point.

pthreads(7), Linux

So, your thread will run until it invokes a syscall which has been defined as a "cancellation point"—usually these are blocking syscalls. See a list of cancellation points here; the true list is OS-dependent.

This assumes that your thread's cancelability type is set to PTHREAD_CANCEL_DEFERRED, which is the default state. If you set the cancability type to PTHREAD_CANCEL_ASYNCHRONOUS, you risk a leak.

Jay Sullivan
  • 17,332
  • 11
  • 62
  • 86