Reentrant Callback

This is something that I saw in ROS.

From ChatGPT:

A reentrant callback is specifically designed to handle nested or recursive invocations without unintended side effects. This design characteristic is especially crucial in multi-threaded or asynchronous environments, where the same function might be called before a previous invocation has completed.

Characteristics of a Reentrant Callback:

  1. Stateless: It doesn’t rely on mutable shared state.
  2. Thread-Safe: If used in a multi-threaded environment, it should properly synchronize access to shared resources.
  3. Idempotent: Multiple invocations produce the same result when provided the same input.
  4. Atomic Operations: It should perform operations that can be safely interrupted and resumed.

Why is it Important?

Reentrant callbacks are critical in systems that need high levels of concurrency and reliability. For example, in real-time systems, web servers, or any system where the callback can be triggered by external events, having a reentrant callback can be essential for maintaining system stability.

Example in C:

Here is a simple example of a reentrant callback in C:

#include <stdio.h>
 
void reentrant_callback(int value, void (*callback)(int)) {
    if (value <= 0) {
        return;
    }
    printf("%d\n", value);
    callback(value - 1, callback);
}
 
void main() {
    reentrant_callback(3, reentrant_callback);
}

In this example, the reentrant_callback function invokes itself as a callback, decreasing the value each time. The function is reentrant because it doesn’t rely on any shared mutable state and safely allows for nested invocations.