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):
We can make this function reentrant by making the sum not a global variable and instead requiring the caller to maintain it:
- int increment(int sum, int i) {
- return sum + i;
- }
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