Main Content

Reentrant Code

Reentrant code is a reusable programming routine that multiple programs can use simultaneously. Operating systems and other system software that use multithreading to handle concurrent events use reentrant code. In a concurrent environment, multiple threads or processes can attempt to read and write static data simultaneously. Therefore, sharing code that uses persistent or static data is difficult. Reentrant code does not contain static data. Calling programs maintain their state variables and pass them into the function. Therefore, any number of threads or processes can share one copy of a reentrant routine.

Generate reentrant code when you want to:

  • Deploy your code in multithreaded environments.

  • Use an algorithm with persistent data belonging to different processes or threads.

  • Compile code that uses function variables that are too large to fit on the stack.

If you do not specify reentrant code, MATLAB® Coder™ generates code that uses statically allocated memory for:

  • Function variables that are too large to fit on the stack

  • Global variables

  • Persistent variables

If the generated code uses static memory allocation for these variables, you cannot deploy the generated code in environments that require reentrant code. If you cannot adjust the static memory allocation size, the generated code can result in static memory size overflow.

When you generate reentrant code, MATLAB Coder creates input data structures for:

  • Function variables that are too large to fit on the stack

  • Persistent variables

  • Global variables

You can then dynamically allocate memory for these input structures. The use of dynamic memory allocation means that you can deploy the code in reentrant environments.

Related Topics