sg-s / xolotl

A MATLAB neuron simulator. Very fast (written in C++). Flexible (fully object oriented). Immediate (live manipulation in MATLAB). Comes with a powerful parameter optimizer. Get started ➡️
https://go.brandeis.edu/xolotl
GNU General Public License v3.0
44 stars 8 forks source link

Use global variables to split up integration loops into different functions #400

Open sg-s opened 5 years ago

sg-s commented 5 years ago
sg-s commented 5 years ago

it looks like global variables persist across multiple calls to the binary -- need to wait for Mathworks support to clarify behaviour.

sg-s commented 5 years ago

apparently global variables do persist. interesting.

alec-hoyland commented 5 years ago

If a variable is instantiated inside of a function and marked as global, it should persist in the workspace. What's surprising to me is that this behavior applies to mex functions too.

The workaround is manual garbage collection at the end of each iteration of a loop.

sg-s commented 5 years ago

The behaviour is stranger than you imagine:

#include "mex.h" 
int wow = 0; 
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { 
void testfunc(void); 
for (int i = 0; i < 1e3; i ++) {testfunc();} 
mexPrintf("wow = %i\n",wow); 
} 
void testfunc() { 
wow++; 
} 

I compile it with mex. Now, calling it multiple times gives the following output:

wow = 1000 
wow = 2000 
wow = 3000 

showing that the global variable "wow" persists across function calls. (where??)

Calling "clear mex" resets the counter

clear mex 
wow = 1000 
alec-hoyland commented 5 years ago

wtf

sg-s commented 5 years ago

apparently this is expected behaviour according to mathworks support

sg-s commented 5 years ago

this is what they had to say:

"mexMakeMemoryPersistent" only applies to memory allocated by MATLAB memory allocation routines such as "mxCalloc", "mxMalloc", "mxRealloc", and the different "mxCreate*" functions (https://www.mathworks.com/help/matlab/create-or-delete-array.html). Global variables in C++ are initialized only once during compilation. The value will persist across subsequent execution of the code, which is why the variable "wow" is increasing in value every time your function is being called. To clear global variables, you can just call clear mex as you have done before. MathWorks does not actively discourage the usage of global variables in MEX files. However, it is up to the developer to exercise caution and keep track of global variables since every function has access to them. Global variables should not cause memory leaks as they are not dynamically allocated. They will reside in the same memory space across subsequent program execution.

github-actions[bot] commented 5 years ago

Stale issue message