Why is the thread in my program cancelling before reaching of the testcancel function? I exepected thread will be cancelled when testcancel called, but it cancelling immediately with a changing cancelstate to enable.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int i = 0;
void proc1()
{
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
for (i = 0; i < 7; i++)
{
if (i == 3) {
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
}
if (i == 5) {
pthread_testcancel();
}
printf("I'm still running! %d\n", i);
sleep(1);
}
}
int main(void)
{
pthread_t thread;
pthread_create(&thread, NULL, (void*)proc1, NULL);
sleep(1);
printf("Requested to cancel the thread\n");
pthread_cancel(thread);
pthread_join(thread, NULL);
printf("The thread is stopped\n");
return 0;
}
Result:
I tried to run it without printf (due to printf is cancellation point too) but it didn't solve the problem.