Reputation: 342
Instead of parfor
loop I want to create 4 threads and write out the code for each individually. What's the syntax for that?
Upvotes: 2
Views: 206
Reputation: 36710
I recommend to use Edric's answer or this solution
(I leave the answer here for the comments.)
Forget about cores, you want to distribute your tasks among your worker processes.
Simple "hack" solution:
n=4
result=cell(4,1)
parfor idx=1:n
switch idx
case 1
r=f()
case 2
r=g(1)
case 3
r=g(2)
case 4
r=h()
end
result{idx}=r
end
For a more advanced solution, I recommend to create individual jobs and submit them. This is explained in detail here. In your case you create a job with four tasks, then you submit it. The biggest advantage of this solution is, that you avoid unnecessary broadcasting of variables.
In both solutions you don't control which worker processes which task, but you typically don't want to do this.
Upvotes: 2
Reputation: 25140
You have two options here. The first is to use parfeval
where you can request several independent function evaluations, like so:
% The following line executes
% out = a(a1, a2, a3) on a worker. (The number 1 is the
% the number of outputs requested from the function evaluation)
% The results can be obtained using
% out = fetchOutputs(f_a);
f_a = parfeval(@a, 1, a1, a2, a3);
% and so on...
f_b = parfeval(@b, 1, b1, b2);
f_c = parfeval(@c, 1, c1);
f_d = parfeval(@d, 1, d1, d2);
You can retrieve the results using fetchOutputs(f_a)
etc.
Another option is to use spmd
like so:
spmd
switch labindex
case 1
a();
case 2
b();
...
end
end
Generally, for independent tasks, I would suggest parfeval
since this approach is not dependent on the number of workers in your parallel pool, whereas the spmd
approach is.
Upvotes: 3