Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 error\n");
    }

    if (pthread_cancel(tid) != 0) { // cancel thread
        printf("cancel error\n");
    }
    pthread_join(tid, (void **)retval); 
    printf("main thread exit\n");
    return 0;
}
like image 452
hel Avatar asked Nov 25 '25 13:11

hel


1 Answers

To have a "cancellation point" which you control, 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 at any cancellation point (such as I/O).

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

like image 117
John Zwinck Avatar answered Nov 27 '25 02:11

John Zwinck



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!