thread cancelation in pthread in linux environment

64 Views Asked by At

I executed the following sample code:

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

static void * thread_func(void *ignored_argument) {
    int s;

    s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    sleep(5);
    s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

         **while (1);**
         sleep(1000);

    printf("thread_func(): not canceled!\n");
    return NULL;
}

int main(void) {
    pthread_t thr;
    void *res;
    int s;

    s = pthread_create(&thr, NULL, &thread_func, NULL);

    sleep(9);
    printf("main(): sending cancellation request\n");
    s = pthread_cancel(thr);


    s = pthread_join(thr, &res);
    if (res == PTHREAD_CANCELED)
        printf("main(): thread was canceled\n");
    else
        printf("main(): thread wasn't canceled (shouldn't happen!)\n");

    exit(EXIT_SUCCESS);
}

when I comment bolded while (1) line (about line 14), thread was cancelled, but when I uncomment this line thread cancellation does not work.

As I understand pthread_cancel, canlcel running and sleeped thread. is it right? if yes please help me about the mentioned code.

linux man page and also search in google

1

There are 1 best solutions below

0
Mathieu On

From the pthread(7) manual:

Cancelation points

POSIX.1 specifies that certain functions must, and certain other functions may, be cancelation points. If a thread is cancelable, its cancelability type is deferred, and a cancelation request is pending for the thread, then the thread is canceled when it calls a function that is a cancelation point. The following functions are required to be cancelation points by POSIX.1-2001 and/or POSIX.1-2008:

  • accept()
  • ...
  • sleep()

So while(1); is not a cancellation point.

To cancel a thread not a a cancellation point, you have to call pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);:

The pthread_setcanceltype() sets the cancelability type of the calling thread to the value given in type. The type argument must have one of the following values:

PTHREAD_CANCEL_DEFERRED

A cancelation request is deferred until the thread next calls a function that is a cancelation point (see pthreads(7)). This is the default cancelability type in all new threads, including the initial thread.

Even with deferred cancelation, a cancelation point in an asynchronous signal handler may still be acted upon and the effect is as if it was an asynchronous cancelation.

PTHREAD_CANCEL_ASYNCHRONOUS

The thread can be canceled at any time. (Typically, it will be canceled immediately upon receiving a cancelation request, but the system doesn't guarantee this.)