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);

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

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

#Task-3
    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

https://docs.julialang.org/en/v1/manual/distributed-computing/
Distributed Computing · The Julia Language}

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);

#Task-1
    if ~isempty(x1)
       for i in 1:size(x1,2)
           Y[i,i] += x1[i];
       end
    end
#Task-2
    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);

#Task-1
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
#Task-2
s2 = @spawnat 2 begin
r[i,i]=zeros(2,2);
    if ~isempty(x2)
       for i in 3:4
           r[i,i] += x2[i];
       end
    end
end
Y[1:2,1:2]= fetch(s1)
Y[3:4,3:4]= fetch(s2)