Saturday 21 October 2017

reentrant function

A function is reentrant if it can be invoked while already in the process of executing. 
That is, a function is reentrant if it can be interrupted in the middle of execution.


For example, the following function is not reentrant.
because the observed value of the summation depends on when and where the function is interrupted (or, in the case of multithreading, how two or more threads race into the function):

  • static int sum = 0;
  •  
  • int increment(int i) {
  • sum += i;
  • return sum;
  • }


  • We can make this function reentrant by making the sum not a global variable and instead requiring the caller to maintain it:

    1. int increment(int sum, int i) {
    2. return sum + i;
    3. }

    How does that relate to it being thread-safe?
    A reentrant function can be invoked, interrupted, and re-invoked. Such a function can be invoked simultaneously by multiple threads if and only if each invocation references or provides unique data and inputs.

    A thread-safe function can be invoked simultaneously by multiple threads, even if each invocation references or provides the same data or input, as all access is serialized.
     

    a reentrant function is more likely to be thread-safe all else equal.

    Writing reentrant code.

    • Do not access mutable global or function-static variables.
    • Do not self-modify code.
    • Do not invoke another function that is itself non-reentrant.

       

    No comments:

    Post a Comment