continues parallel execution of system command in matlab
Show older comments
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 Comment
xiaohuo
on 1 Mar 2022
Have you solved this problem? Thanks.
Answers (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.
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!