Working around segmentation faults that occur in parallel due to a non-thread-safe API function

[亡魂溺海] 提交于 2019-12-12 02:58:06

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/10240387/working-around-segmentation-faults-that-occur-in-parallel-due-to-a-non-thread-sa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!