Вопрос

I have read may threads on re-entrant subjects on SO as as well as on http://en.wikipedia.org/wiki/Reentrancy_(computing).

I might get the ideas of re-entrant functions. But when I read the example on the wiki site, I really confused.

The first example:

int t;

void swap(int *x, int *y)
{
 t = *x;
 *x = *y;
 // hardware interrupt might invoke isr() here!
 *y = t;
}

void isr()
{
 int x = 1, y = 2;
 swap(&x, &y);
}

As the site explained: " It still fails to be reentrant, and this will continue to cause problems if isr() is called in the same context as a thread already executing swap()." => What kinds of prolems that might happen here? the swapping result is not correct? Or value of t variable is modified?

And the second example, which improved the first one:

int t;

void swap(int *x, int *y)
{
 int s;

 s = t; // save global variable
 t = *x;
 *x = *y;
 // hardware interrupt might invoke isr() here!
 *y = t;
 t = s; // restore global variable
}

void isr()
{
 int x = 1, y = 2;
 swap(&x, &y);
}

How this improves the first one? Does that mean that the variable t is kept unchanged inside the swap() function?

Это было полезно?

Решение

Re-entrant means that the function can be interrupted at any point, and be able to correctly finish executing after the interruption, even in cases when the same function is called one or more times in the interrupted state.

The crucial part here is that the invocation of the function called in the interrupted state must finish before the original call state is restored. This is the main difference between re-entrancy and thread safety: in order to be thread-safe, a function must be able to proceed even if the interrupting invocation is unfinished before the control gets back to the original call.

That's why the second version of the swap is re-entrant: it always leaves t in an unchanged state upon exiting, so entering and exiting swap in the middle of an interrupted call will not alter the global state seen by the interrupted invocation.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top