Multithreading with N thread
    7 views (last 30 days)
  
       Show older comments
    
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
3 Comments
Answers (1)
  OCDER
      
 on 23 Jun 2018
        
      Edited: OCDER
      
 on 26 Jun 2018
  
      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 Comments
  OCDER
      
 on 26 Jun 2018
				Yup, that solution is correct. Create a job with N independent tasks to be run by W workers.
See Also
Categories
				Find more on Parallel Computing Fundamentals 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!

