|
Syntax #include <pthread.h> int pthread_cancel(pthread_t thread); Threadsafe: Yes Signal Safe: No |
The pthread_cancel() function requests cancelation of the target thread. The target thread is canceled, based on its cancelability state.
Cancelability consists of 3 separate states (disabled, deferred, asynchronous) that can be represented by 2 boolean values.
| Cancelability | Cancelability State | Cancelability Type |
|---|---|---|
| disabled | PTHREAD_CANCEL_DISABLE | PTHREAD_CANCEL_DEFERRED |
| disabled | PTHREAD_CANCEL_DISABLE | PTHREAD_CANCEL_ASYNCHRONOUS |
| deferred | PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED |
| asynchronous | PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_ASYNCHRONOUS |
The default cancelability state is deferred.
When cancelability is disabled, all cancels are held pending in the target thread until the thread changes the cancelability. When cancelability is deferred, all cancels are held pending in the target thread until the thread changes the cancelability, calls a function which is a cancelation point or calls pthread_testcancel(), thus creating a cancelation point. When cancelability is asynchronous, all cancels are acted upon immediately, interrupting the thread with its processing.
It is recommended that your application not use asynchronous thread cancelation via the PTHREAD_CANCEL_ASYNCHRONOUS option of pthread_setcanceltype(). See the common user errors section of this document for more information.
The following functions are cancelation points:
Note that in the OS/400 implementation of threads, the initial thread is special. Termination of the initial thread via pthread_exit(), pthread_cancel() or any other thread termination mechanism terminates the entire process.
None.
If pthread_cancel() was not successful, the error condition returned usually indicates one of the following errors. Under some conditions, the value returned could indicate an error other than those listed here.
#include <pthread.h>
#include <stdio.h>
#include "check.h"
void *threadfunc(void *parm)
{
printf("Entered secondary thread\n");
while (1) {
printf("Secondary thread is looping\n");
pthread_testcancel();
sleep(1);
}
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread;
int rc=0;
printf("Entering testcase\n");
/* Create a thread using default attributes */
printf("Create thread using the NULL attributes\n");
rc = pthread_create(&thread, NULL, threadfunc, NULL);
checkResults("pthread_create(NULL)\n", rc);
/* sleep() isn't a very robust way to wait for the thread */
sleep(2);
printf("Cancel the thread\n");
rc = pthread_cancel(thread);
checkResults("pthread_cancel()\n", rc);
/* sleep() isn't a very robust way to wait for the thread */
sleep(3);
printf("Main completed\n");
return 0;
}
Output
Entering testcase Create thread using the NULL attributes Entered secondary thread Secondary thread is looping Secondary thread is looping Cancel the thread Main completed