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.

To deploy the generated code, you must create a main function that:

  • Includes the header file primary_function_name.h.

  • Allocates memory for the global memory allocation structure primary_function_nameStackData.

  • If the algorithm uses persistent or global data, allocates memory for the global structure primary_function_namePersistentData.

  • Calls these functions:

    • primary_function_name_initialize.

    • primary_function_name.

    • primary_function_name_terminate.

When you convert a MATLAB function to a C/C++ library function or a C/C++ executable, MATLAB Coder generates two housekeeping functions. Call these housekeeping functions in the code that calls the generated C/C++ function. For more information, see Deploy Generated Code.

Related Topics