Skip to content
Advertisement

pthread_cancel and cancellation point

I’m learning the pthread_cancel function and testing whether thread would be cancelled when it doesn’t reach cancellation point. Thread is created by default attribute and make it running in add loop. But when cancellation request was sent and thread exit immediately. It doesn’t reach cancellation point and I think it should not respond to the request immediately.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_func(void *arg)
{
    int i;
    int j;
    int k;

    k = 1;

    /* add operation */
    for (i=0; i<1000; ++i) {       
        for (j=0; j<10000;++j) {
             ++k;              // maybe for(z=0; z<10000; ++z) added would 
                               // be better
        }
    }
    return (void *)10;
}

int main(void)
{
    char *retval;
    pthread_t tid;

    if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {                 
        printf("create errorn");
    }

    if (pthread_cancel(tid) != 0) { // cancel thread
        printf("cancel errorn");
    }
    pthread_join(tid, (void **)retval); 
    printf("main thread exitn");
    return 0;
}

Advertisement

Answer

To have a “cancellation point” you need to use pthread_setcancelstate() to disable cancellation at the start of your thread function and then enable it when you want. When a new thread is spawned, it has the cancel state “enabled” meaning it can be canceled immediately at any time.

Perhaps more to the point, you probably shouldn’t use pthread_cancel() at all. For more on that, see here: Cancelling a thread using pthread_cancel : good practice or bad

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement