'pthread Deferred Cancelation

My Expectation is, the thread must print integers from 0 to 99 and then only it should get canceled because the cancellation point is outside the loop, but here we can see thread cancels arbitrarily. Can somebody pls help me understand the behavior? Whats the point of Deferred Cancellation and cancellation point if the thread still cancels arbitrarily.

void *r1(void *args)
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0);
char str[100];
for (int t = 0; t < 100; t++)
{
    printf("%d\n", t);
}
pthread_testcancel();
}

int main()
{

pthread_t t1;
void *t1_ret = NULL;
pthread_attr_t attr1;
pthread_attr_init(&attr1);
pthread_create(&t1, 0, r1, 0);
printf("Cancelling thread\n");
if (pthread_cancel(t1) == -1)
{
    perror("Failed to cancel thread\n");
    return 1;
}
printf("Thread cancelled and cleaned up successfully\n");
printf("Returning from main\n");
pthread_exit(0);
return 0;
}
output:

Cancelling thread
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Thread cancelled and cleaned up successfully
Returning from main


Solution 1:[1]

Got it. printf( ) --> write( ), and write( ) is a inbuilt cancellation point.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhishek Sagar