简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM