One may use lists of parameters for each kernel in conjunction with $KernelID
. On each kernel, $KernelID
simply evaluates on a number of the kernel. So all we have to do is to design the code in a way that it depends on $KernelID
. In this case, we use $KernelID
in order to index into the lists of parameters (indexing with [[ ]]
, the short form of Part
).
alist = {9, 8, 7, 6};
blist = {10, 20, 30, 40};
f[x_] := a x + b x
ParallelEvaluate[
Block[{a = alist[[$KernelID]], b = blist[[$KernelID]]},
f[1]
]
]
{19, 28, 37, 46}
The drawback of this method is that the outcome depends on the number of kernels...
A better approach might be to use, e.g., ParallelTable
. Here an example that hopefully illuminates what is going on:
f = {x, a, b} \[Function] a x + b x;
alist = {9, 8, 7, 6};
blist = {10, 20, 30, 40};
ParallelTable[
Row[{"Kernel ", $KernelID, " computes ", i -> f[1, alist[[i]], alist[[i]]], "."}],
{i, 1, Length[alist]}
]
{Row[{"Kernel ", 4, " computes ", 1 -> 18, "."}], Row[{"Kernel ", 3,
" computes ", 2 -> 16, "."}], Row[{"Kernel ", 2, " computes ", 3 ->
14, "."}], Row[{"Kernel ", 1, " computes ", 4 -> 12, "."}]}
A further, more functional oriented way could be ParallelMap
:
ParallelMap[
abpair \[Function] Row[{"Kernel ", $KernelID, " computes ", f[1, abpair[[1]], abpair[[2]]], "."}],
Transpose[{alist, blist}]
]
{Row[{"Kernel ", 4, " computes ", 19, "."}], Row[{"Kernel ", 3, "
computes ", 28, "."}], Row[{"Kernel ", 2, " computes ", 37, "."}], Row[{"Kernel ", 1, " computes ", 46, "."}]}
Block[{a=1,b=1},f[x]]
... $\endgroup$ParallelEvaluate
doesn't permit to call in parallel the same function with different agruments (say f[1] and f[2] in parallel).I think the only way to launch the same function with different parameters withParallelEvaluate
is to use a shared variable (or someRandom..
in the kernels). $\endgroup$