To avoid problems the function should probably avoid interacting with matlab in any way. Printouts should be directed away from the matlab command window (e.g. to a terminal screen or a file).
Workaround for using printf within openmp parallel regions in mex files?
8 次查看(过去 30 天)
显示 更早的评论
Hello!
I wrote parallel c code with openmp. In several places, the code checks for errors and in case they are found it prints out a message (printf()), and exits (exit()).
Then I made a mex function from this code.
One problem to consider is that its forbidden to use printf because the header file mex.h redefines it as mexPrintf which is not thread safe. Thus all the error messages can not be printed, and the program just exits without giving a clue about the nature and location of the error.
Consider the following suggestion for a workaround: Put the call to printf in a function my_printf() which sits in a seperate file that does not include the mex.h file. This function can look somthing like
void my_printf(char * error_message){
printf("%s \n", error_message);
}
Since this function is in a file which does not include mex.h the printf is not redefined to mexPrintf and behaves just like a "normal" c printf, i.e. thread safe.
Other workarounds can be to use output functions which are not redefined to mex API functions in mex.h. For example, printing error messages to a file using fprintf, or printing to screen with puts().
Does anyone have experience with this? Might it work?
回答(2 个)
Jan
2011-7-27
You can use a semaphore to block concurrent calls of mexPrintf. One idea is to create an dedicated thread for writing messages, which blocks further calls, until the message is written.
Because this is not a Matlab related problem, I suggest to ask Google for "multithread debug" or similar keywords.
4 个评论
Jan
2011-7-27
@Ilan: There is no simple way for output in multitreaded programs. Even simple logging and debug information need additional effort. A cheap solution could be to write in a (memory mapped) file and forward the file's contents to mexPrintf, when all threads have returned. But even this should be checked for beein thread-safe.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!