Matlab多线程 [英] Multithreading with Matlab
问题描述
我正在Matlab上的一个项目中,我们必须优化性能,并且我正在考虑并行化由.m文件进行的几个函数调用.
I'm working on a project on Matlab where we have to optimize the performance, and I was thinking about parallelizing a couple of function calls that were made from a .m file.
这个想法很简单,从Matlab文件(.m)调用编译为MEX的C文件,然后从该C文件创建几个线程,并从每个线程中调用matlab函数.
The idea was simple, from a Matlab file (.m) call a C file compiled as MEX, and from that C file, create a couple of threads and call back the matlab functions from each thread.
理论可行,我可以创建线程,也可以调用matlab函数,问题是我无法从线程调用matlab函数:
The theory works, I can create the threads, and I can also call the matlab function, the problem is that I cannot call the matlab function from the thread:
//Global variables
mxArray **g_plhs;
mxArray **g_prhs;
int g_nlhs;
int g_nrhs;
//Thread function
DWORD WINAPI my_function( LPVOID lpParam )
{
mexCallMATLAB(g_nlhs,g_plhs,g_nrhs,g_prhs,"matlab_function");
return 0;
}
//Main function
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
DWORD dwThreadIdArray[MAX_THREADS];
HANDLE hThreadArray[MAX_THREADS];
g_plhs = plhs;
g_prhs = prhs;
g_nlhs = nlhs;
g_nrhs = nrhs;
hThreadArray[0] = CreateThread(
NULL,
0,
my_function,
NULL,
0,
&dwThreadIdArray[0]);
WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
for(i=0; i<MAX_THREADS; i++)
{
CloseHandle(hThreadArray[i]);
}
}
使用matlab时,我们对该选项有任何限制吗? 有人尝试过这样的事情吗?
Do we have any restriction on that option when working with matlab? Has somebody tried something like this?
是否有不需要Parallel Toolbox的选项?
Is there any option that doesn't require Parallel Toolbox?
推荐答案
您只能从MATLAB主线程调用mx *和mex *函数.您可以编写多线程MEX文件,只要这些文件能在mx界面以下的水平上发挥作用.如果需要多个MATLAB解释器,则需要多个MATLAB进程.一种方法是通过@You指出的并行计算工具箱".这使您可以同时运行PARFOR
循环和SPMD
块.
You can only call the mx* and mex* functions from the MATLAB main thread. You can write multithreaded MEX files providing these do their work at a level below the mx interface. If you want multiple MATLAB interpreters, you need multiple MATLAB processes. One way is through the Parallel Computing Toolbox as pointed out by @You. This gives you PARFOR
loops and SPMD
blocks for running things simultaneously.
这篇关于Matlab多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!