Search topics...
Operating Systems & RTOSReentrant Functions and volatileintermediate

What makes a function reentrant and why does it matter in embedded systems?

0 upvotes
Practice with AISoon
Study the fundamentals first — Operating Systems & RTOS topic page

A function is reentrant if it can be safely interrupted during execution and called again ("re-entered") before the first invocation completes, without producing incorrect results. This property is essential in embedded systems because ISRs can preempt tasks at any point and may call the same function the task was executing.

For a function to be reentrant, it must: (1) not use static or global variables (or, if it does, protect them with proper synchronization); (2) not modify its own code (not relevant in modern systems with Harvard architecture or read-only flash); (3) not call non-reentrant functions. The function should operate only on its parameters and local variables, which live on the stack and are therefore unique to each invocation.

Common non-reentrant functions include strtok (uses an internal static pointer), rand (uses static state), and printf/malloc (use global data structures). Their reentrant counterparts are typically suffixed with _r (e.g., strtok_r). In practice, if a function must use shared state, you can make it thread-safe (not exactly the same as reentrant) by protecting the shared state with a mutex — but this only works for task-to-task concurrency, not for ISR-to-task concurrency, since ISRs cannot take mutexes. For ISR safety, you must either avoid shared state entirely or use lock-free techniques.

Source: Operating Systems & RTOS Q&A