continues parallel execution of system command in matlab

I need to run a specific number of FEM analysis (in FEA software) by using 'system' command in Matlab. For example, I have to run 20 FEA, and since I have a 4core cpu I can run 4 analysis simultaneously. I guess, I have to create a for loop to run 'system' 4 times. But the question is how to queue the other jobs to wait until one of the 4 running simulations is finished and a slot gets empty so another FEA can be started. Therefore, always 4 FEA is running until all 20 are finished. Here is an example of for loop:
njobs=20
ncpu=4;
for i=1:ncpu
command=['runFEA',num2str(i),'!'];
C(i)=system(command);
end

回答(1 个)

With .NET under Windows:
batFile = 'c:\temp\example.bat';
startInfo = System.Diagnostics.ProcessStartInfo('cmd.exe', ...
sprintf('/c "%s"', batFile));
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc = System.Diagnostics.Process.Start(startInfo);
if isempty(proc)
error('Failed to launch process');
end
while true
if proc.HasExited
fprintf('\nProcess exited with status %d\n', proc.ExitCode);
break
end
fprintf('.');
pause(1.0);
end
A Java method:
batFile = 'c:\temp\example.bat';
cmd = sprintf('cmd.exe /c "%s"', batFile);
runtime = java.lang.Runtime.getRuntime();
proc = runtime.exec(cmd);
% a = proc.getInputStream;
% b = getOutputStream;
while true
% a.read; % This causes a stall on my Windows 10/Matlab R018b
% b.flush;
try
exitCode = proc.exitValue();
fprintf('\nProcess exited with status %d\n', exitCode);
break;
catch
err = lasterror(); % old syntax for compatibility
if strfind(err.message, 'process has not exited')
fprintf('.');
pause(1.0);
else
rethrow(err);
end
end
end
You can modify the methods to start a new instance of the 20 jobs, when one instance is ready.

2 个评论

I am not sure if I understood correctly? is this executable in Matlab, or I should use .net? Because I need to run it in Matlab and I dont want to go out of Matlab environment.
Would you please explain more how .net works in MATLAB platform?
Thanks.

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息

提问:

2017-6-21

评论:

2022-3-1

Community Treasure Hunt

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

Start Hunting!

Translated by