Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.4a |
both | POSIX(ON) |
#define _OPEN_THREADS
#include <pthread.h>
int pthread_cancel(pthread_t thread);
#define _UNIX03_THREADS
#include <pthread.h>
int pthread_cancel(pthread_t thread);
Requests that a thread be canceled. The thread to be canceled controls when this cancelation request is acted on through the cancelability state and type.
A thread that is joined on a thread that is canceled has a status of -1 returned to it. For more information, refer to pthread_join() — Wait for a thread to end.
pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.
Special behavior for C++: Destructors for automatic objects on the stack will be run when a thread is canceled. The stack is unwound and the destructors are run in reverse order.
Special behavior for SUSv3 : Single UNIX Standard, Version 3 defines new symbols for cancelability state and type. These are equivalent to the symbols described above and must be used when compiling in the SUSv3 namespace. The symbols for state are PTHREAD_CANCEL_ENABLE and PTHREAD_CANCEL_DISABLE. Symbols for type are PTHREAD_CANCEL_DEFERRED and PTHREAD_CANCEL_ASYNCHRONOUS.
If successful, pthread_cancel() returns 0. Success indicates that the pthread_cancel() request has been issued. The thread to be canceled may still execute because of its interruptibility state.
Special behavior for Single UNIX Specification, Version 3:
If unsuccessful, pthread_cancel() returns an error number to indicate the error.
⁄* CELEBP14 *⁄
#define _OPEN_THREADS
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int thstatus;
void * thread(void *arg)
{
puts("thread has started. now sleeping");
while (1)
sleep(1);
}
main(int argc, char *argv[])
{
pthread_t thid;
void *status;
if ( pthread_create(&thid, NULL, thread, NULL) != 0) {
perror("pthread_create failed");
exit(2);
}
if ( pthread_cancel(thid) == -1 ) {
perror("pthread_cancel failed");
exit(3);
}
if ( pthread_join(thid, &status)== -1 ) {
perror("pthread_join failed");
exit(4);
}
if ( status == (int *)-1 )
puts("thread was cancelled");
else
puts("thread was not cancelled");
exit(0);
}
thread has started. now sleeping
thread was canceled