Hi @Leonardo, it appears you're running into a known behavior where MATLAB/Simulink freezes at the end of a simulation with a custom S‑Function that uses an external multithreaded library. Since traditional MATLAB commands can't debug this, here are some strategies to debug the issue without relying on non‑MATLAB tools: 1. Attach a Debugger After the Hang
Run your model under the MATLAB IDE, and when Simulink hangs:
Once attached, inspect threads with:
- This shows the current call stack of all threads—useful to see if any are blocked in library cleanup or waiting on a mutex.
2. Check for Threading Deadlocks
Even if you force single-thread mode, your library may still spawn internal threads internally. A deadlock during termination (e.g., joining threads or cleaning shared resources) would cause MATLAB to hang silently.
- Ensure all threads are properly joined.
- Ensure all mutexes, locks, or semaphores are released before mdlTerminate completes.
3. Enable Diagnostic Print Statements
Insert debugging prints in mdlStart, mdlOutputs, and mdlTerminate to log important steps. Use ssPrintf(...) for better Simulink compatibility:
ssPrintf("Entering mdlTerminate, stopping nanothread context...\n");
ssPrintf("nanothread context shut down, exiting mdlTerminate...\n");
This helps identify where the hang occurs.
4. Test Outside MATLAB
Create a standalone test executable that initializes and terminates your library just as the S-function does. Run it repeatedly in a loop—even crashing once via simulated library failure—to check if it leaks resources or hangs on shutdown. This isolates whether the issue is library-specific or MATLAB-specific.
5. Try SS_OPTION_EXCEPTION_FREE_CODE
On some platforms, enabling exception-safe code in the S-function helps avoid deadlocks or crashes during cleanup. In your mdlInitializeSizes, apply:
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
This might prevent unexpected behavior during teardown. Hope this helps!