Workaround for using printf within openmp parallel regions in mex files?
이전 댓글 표시
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일
1 개 추천
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
Ilan
2011년 7월 27일
Walter Roberson
2011년 7월 27일
The C programming language does *not* define printf() to be thread safe. The C programming language does not define anything about threads. There are different threading paradigms with different behaviors. One of the more common of those is POSIX Threads. POSIX might define the threading behavior of printf(), but C does not.
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.
Ilan
2011년 7월 28일
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!