#include #include #include #include int i = 0; void * thread_func(void *arg) { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); printf("YOU WILL NOT STOP ME!!!\n"); for (i=0; i < 4; i++) { sleep(1); printf("I'm still running!\n"); } printf("Now you can stop me!\n"); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); //pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); //pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); //printf("Wait when you stop me!\n"); pthread_testcancel(); } int main(int argc, char * argv[]) { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); while (i < 1) sleep(1); pthread_cancel(thread); printf("Requested to cancel the thread\n"); pthread_join(thread, NULL); printf("The thread is stopped.\n"); return EXIT_SUCCESS; }