Multithreading with N thread
10 次查看(过去 30 天)
显示 更早的评论
How I can create N threads that run specific function parallely? I don't matter if it's slower than single thread and I don't matter if I'm adding a lot overhead, but I need that N instaces of function will be runned "potentially parallely". For exemple if I have 8 thread I would that all 8 functions associated to thread will be execute concurrently and I could have that first thread is at 20% of progress and the second thread at 17% of progress and so on for all threads that i want to create! I report this simple test code that I'm trying to execute:
n = 8;
input = cell(1,n);
for i = 1:n
input{i} = {i};
end
cluster = parcluster;
cluster.NumThreads = n;
j = createJob(parcluster);
tasks = createTask(j, @run, 0, input);
submit(j)
wait(j)
function seed = run(seed)
disp('prova')
for index = 1:100
dlmwrite(sprintf('/tmp/Seed_%d_progress.txt', seed), index);
pause(0.4);
end
end
I hope I was clear in my spiegation
回答(1 个)
OCDER
2018-6-23
编辑:OCDER
2018-6-26
NEW ANSWER
Matlab has it own scheduler called Matlab job scheduler (MJS). This will handle all your job scheduling. If you want a custom job scheduler, you'll have to use a third party job scheduler. Read:
OLD ANSWER
parfor will execute each iteration in parallel depending on how many cores you haves. If you have a quad-core processor, you can only do 4 at a time.
parfor j = 1:8 %treat each "iteration" as each worker
Out{j} = runFun(Input{j}); %slice your inputs and outputs so each worker are independent of eachother
end
%NOTE! Do NOT label your function "run" as that is a built-in matlab function.
Now, if you want the progress bar for each worker though, that's a little bit tricky. There are workarounds to that as seen in the Mathwork File Exchange site.
13 个评论
OCDER
2018-6-26
Yup, that solution is correct. Create a job with N independent tasks to be run by W workers.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!