tags:

views:

454

answers:

4
void reverse_string(char* string, int str_size) {
    char tmp;
    int i = 0;
    int j = str_size - 1;
    while (i < j) {
        tmp = string[i];
        string[i] = string[j];
        string[j] = tmp;
        ++i;
        --j;
    }
}

I think this function is reentrant, since it doesn't use any global variable. It only modifies the arguments.

My question is: is this function reentrant? if it is, is my argument good enough?

thanks in advance

+7  A: 

Yes, you're right, it's reentrant. It only affects its parameter and its local variables.

The only way different instances could interfere would be if you passed them pointers to the same buffer.

There's a good definition of reentrant on Wikipedia and your function clearly meets all the terms.

RichieHindle
+10  A: 

Yes, this is a reentrant function. Reentrant functions are defined as those that can be called whilst they are themselves executing (either due to recursion, or concurrency). In this case, recursion is moot, and you are concurrently safe (assuming differing parameters).

Your argument is fine - there's no global or shared state being accessed either explicitly or implicitly, so reentrancy is ensured. This is a combination of both your explicit code and the semantics of C. Other languages and APIs may not have this property.

Edit: On double checking, the ISO C standard doesn't seem to force the thread safety of strlen. As such, there is a tiny possibility that you could be using a C standard library with a non-thread safe strlen and as such, inherit non-reentrancy from it.

Adam Wright
+2  A: 

Yes, it's reentrant as it only modifies its arguments

Wikipedia provides some nice points on what have to be provided to be reentrant:

To be reentrant, a computer program or routine:

  • Must hold no static (or global) non-constant data.
  • Must not return the address to static (or global) non-constant data. Must work only on the data provided to it by the caller.
  • Must not rely on locks to singleton resources.
  • Must not modify its own code.[1] (unless executing in its own unique thread storage)
  • Must not call non-reentrant computer programs or routines.
nos
+1  A: 

You would need to assume (or verify) that strlen is reentrant (which it probably is).

ChrisW