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
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);from within the thread-callback make any difference?while (1);is undefined behaviour (UB) in C++ (but not in C) so the language matters a lot. Programs containing UB are ill-formed and compilers are free to generate wrong code with weird unexpected behaviours (spoil : optimizers actually often do that).sleep), many can be, andwhile(1);is apparently not.