MWB
MWB

Reputation: 12617

Is Wikipedia wrong about reentrancy?

https://en.wikipedia.org/wiki/Reentrancy_(computing) (as of Dec 9, 2016) states that the following code is reentrant, despite modifying a global variable, because swap leaves it unchanged:

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
}

However, what if swap is interrupted in any other number of places? Is this function reentrant, according to the definition of the term?

By the way, this article is cited as a source elsewhere on SO -- perhaps someone should improve it.

Upvotes: 3

Views: 139

Answers (2)

chqrlie
chqrlie

Reputation: 145307

You are aware that this swap() function is written in a deliberately bogus way. Even for the purpose of illustrating the concept, it would be better to make t a local variable with static storage class. This way, we could assume that t is not modified elsewhere.

At first sight, the function could be called from an interrupt service routine even if the interruption occurred during the execution because, as they mention, swap restores the value of its private global (useless) state upon exit. To this regard, it can be considered reentrant (asynchronous reentrancy).

For more complicated functions, that call back user supplied code, whether such callbacks can in turn call the function is also a criteria for reentrancy (synchronous reentrancy), but it does not apply here as swap() does not call anything.

The problem is hardware has become quite tricky nowadays, and unless you are programming to a simple embedded processor, fiddling with global variables from interrupt routines can have surprising side effects. t should be made volatile to prevent some of these, but not all.

On a side note, if swap() were to be called by different preemptive threads, the calls and return sequences could be interleaved, a situation that is not handled by the function, not to mention that accesses to the global variable t are not guaranteed to be atomic... swap is definitely not thread safe.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215617

To answer the question it's necessary to observe that "reentrant" is an overloaded term with several accepted meanings, some of them ranging from "stretch" to "blatantly incorrect".

I would say the function is synchronously (but not asynchronously) reentrant, and certainly not thread-safe. That's rather vacuous here since it doesn't call any other functions, but it would be meaningful if it called a callback function which could then call back into this function.

If there were proper use of volatile types, the function could plausibly be asynchronously reentrant (but still not thread-safe).

Upvotes: 2

Related Questions