I see saying global variable update makes a function non-reentrant, this makes sense. But I do not understand why making local copy and restore can resolve it.
Here is an example:
int global_n = 10;
1 void foo()
2 {
3 int local_n = global_n;
4 global_n *= 10;
5 if (global_n < 100) {
6 printf("double digits\n");
7 } else {
8 printf("not double digits\n");
9 }
10 printf("%d\n", global_n);
11 global_n = local_n;
12 }
Let's say the first run of foo() executed line 4, now global_n is 100 and the run is interrupted by another run of foo(), and line 4 of this 2nd run made global_n 1000. So this function is still not reentrant.
Am I right?
Reference: Here is the quote from GNU libc got me asking the above question- if you want to call in a handler a function that modifies a particular object in memory, you can make this safe by saving and restoring that object.
I replaced "memory" with global variable.