Question

I am currently coding a MEX file in MATLAB to run experiments in parallel using the parfor function in MATLAB 2012a. The MEX file does some very straightforward numerical tasks but relies on the CPLEX 12.4 API from IBM.

Although my MEX file works sequentially, I will inevitably receive "random" segmentation fault when I run in in parallel. After sending a stack trace of the segmentation fault to MATLAB, they have suggested that the error originates from the "putenv()" function from the C library, which is apparently not thread-safe.

I do not use the putenv() function in my MEX code, but it turns out that one of functions that I absolutely have to call from the CPLEX 12.4 does use it. I'm wondering if there is anything I could do to avoid the segmentation faults that come as a result of this function. Someone previously suggested "locking my bits" and "using semaphores" but I'm really little over my head when it comes to these concepts.

Any advice or direction would be very much appreciated.

Was it helpful?

Solution

It turns out that the violation occurs since I use the CPLEX MATLAB API in my MATLAB code and the CPLEX C API in my MEX code at the same time. Both APIs use the putenv() function, which is not thread-safe. In particular, the crash occurs whenever two threads try to use the putenv() function at the same time (either in the MEX file or the MATLAB code).

The fix is to use the package and add a mutex_lock / mutex_unlock around the functions that use putenv() in C and MATLAB (i.e. CPXopenCPLEX in C / Cplex() in MATLAB). More information and exact code to create the mutex_lock / mutex_unlock can be found in the following post on the CPLEX forums

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top