How to use OpenMP properly from C++ static library?

조회 수: 10 (최근 30일)
hH
hH 2022년 3월 11일
답변: Infinite_king 2024년 1월 10일
Hi,
I am trying to incooperate a static library written in C++ in Matlab. The C++ static library uses OpenMP for parallel processing. ;
I have built the library interface following https://uk.mathworks.com/help/matlab/build-matlab-interface-to-c-library.html. I am using Windows.
When I call the C++ library from Matlab, it works, but parallel processing is not working and it only runs in serial. In Matlab, the compiler has not been changed. MEX configured to use 'Microsoft Visual C++ 2019 (C)' for C language compilation
How do I setup Matlab or generate library interface properly to use OpenMP of the C++ library?
Thanks,
Hein
  댓글 수: 3
hH
hH 2022년 3월 11일
Thanks for your reply.
Yes, I check the number of threads avaiable from the system and try to run with that many thread. I use the following set up.
The nThreads value printed out by fprintf is multiple (e.g. 4).
The library also seems to work with OpenMP properly if I am calling the library from another C++ application.
Thanks.
int nThreads = omp_get_max_threads() - 1;
fprintf(stderr, "Num. threads = %d\n", nThreads);
#pragma omp parallel for num_threads(nThreads)
James Tursa
James Tursa 2022년 3월 11일
Can you show the code for how you are calling the library functions?

댓글을 달려면 로그인하십시오.

답변 (1개)

Infinite_king
Infinite_king 2024년 1월 10일
Hi,
As per my understanding you are able to use the library from MATLAB but the operations are not being performed in parallel.
To enable OpenMP support for your C++ library when using it in MATLAB through MEX, you need to ensure that the OpenMP flags are correctly set during compilation. Since you're using Microsoft Visual C++ 2019, you need to include the OpenMP flag (/openmp) while compiling.
Follow the below troubleshooting steps to possibly resolve the issue.
  1. Make sure to compile the library with the same compiler that you are using with MATLAB.
  2. Pass the OpenMP flag (/openmp) while compiling Interface.
  3. Change the Mex configuration file or pass the OpenMP flag while compiling mex. Refer the following link for more information, https://www.mathworks.com/help/matlab/ref/mex.html#btw193g-1
  4. Checkout the following answer, you may find it useful, https://www.mathworks.com/matlabcentral/answers/237411-can-i-make-use-of-openmp-in-my-matlab-mex-files
Hope this is helpful.

카테고리

Help CenterFile Exchange에서 C Shared Library Integration에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by