# Can I distribute several tasks over several workers?

Hello,
How can I distribute several tasks on several workers? Such as there are three tasks below (in this case , the three tasks are writing on the same variable Y):

``````x1=[1 3 4 5];
x2=[1 3 4 5];
x3=[1 3 4 5];
Y=zeros(4,4);

if ~isempty(x1)
for i in 1:size(x1,2)
Y[i,i] += x1[i];
end
end

if ~isempty(x2)
for i in 1:size(x2,2)
Y[i,i] += x2[i];
end
end

if ~isempty(x3)
for i in 1:size(x3,2)
Y[i,i] += x3[i];
end
end
``````

Avoid the data race and partition ranges of i.

1 Like

Actually, in this case the range of i is from 1:4 for x1, x2, and x3, but in other cases in my code it is different so the partition of i ranges is hard to achieve.
If there is no common variable Y between the tasks, what is the possible way to run a task (set of lines) on a worker?

I was just trying to deter you from attempting to write to the same variable. Otherwise, it sounds like you are asking about basic distributed computing. See

and particularly:

https://docs.julialang.org/en/v1/manual/distributed-computing/#Data-Movement

Noted,
So, if I want to parallelize the below code,

``````x1=[1 3 4 5];
x2=[1 3 4 5];
Y=zeros(4,4);

if ~isempty(x1)
for i in 1:size(x1,2)
Y[i,i] += x1[i];
end
end
if ~isempty(x2)
for i in 1:size(x2,2)
Y[i,i] += x2[i];
end
end
``````

Can I write the below one?

``````\$ ./julia -p 2
@everywhere x1=[1 3 4 5];
@everywhere x2=[1 3 4 5];
Y=zeros(4,4);

s1 = @spawnat 1 begin
r[i,i]=zeros(2,2);
if ~isempty(x1)
for i in 1:2
r[i,i] += x1[i];
end
end
end