Main Content

Call Reentrant Code in a Multithreaded Environment

To call reentrant code, create a main function that:

  • Includes the header file primary_function_name.h.

  • For each thread, 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. If the threads communicate, allocate this memory once for the root process. Otherwise, you can allocate memory per thread.

  • Contains a thread function that 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 functions in the code that calls the generated C/C++ function. For more information, see Deploy Generated Code.

  • Initializes each thread and passes in a pointer to the memory allocation structure as the first parameter to the thread function.

  • Frees up the memory used for global structures.

Multithreaded Examples