It is a known problem to exit mex functions from matlab. However, by googling I have finally found an idea to a workaround. If I create a mex file that runs on a separate thread and returns an exitcode, eg true, when it is finished I would be able to have a matlab loop in a main thread, that could be terminated the ordinary way with ctrl+c. If I enclose it in a try-catch block, the catch would set in on ctrl+c and there I would run a function mexCancel. However, I am not really sure how to create this mexCancel function.
The problem would be to clean up all resources. The function I want to do this for is load. The first step would be to create a separate mex function myLoad that calls load. Then I would need to create mexCancel that cleans up from myLoad (and from load).
Does anyone have an idea of how to achieve this without creating memory leaks?
There is functionality supported by windows to force a termination of a thread (eg terminateThread), but the problem with these functions is that the simply quits the thread with no cleaning. I am not really sure how load works since it is a built in function, so I do not know exactly what have to be done in this case.