Search code examples
matlabparallel-processingsynchronizationparfor

Synchronization in Matlab


I'm processing data in parallel using parfor in this way:

iteration = 10;
result = zeros(1, iteration);

matlabpool open local 2
    parfor i = 1:iteration
        data = generate_data();
        result(i) = process_data(data);
    end
end
matlabpool close

It works fine, but I have one problem. My function generate_data generates unique data (i.e. 0, 1, 2, 3, 4 ...) but in practice sometimes I give same value two times (and I give 0, 1, 1, 2, 3, 4, 4, 5, ...). In simple my function looks like this:

function data = generate_data()

persistent counter generated_data;

if(isempty(counter))
    counter = 1;
    generated_data = [0 1 2 3 4 5 6 7 8 9]; 
end

data = generated_data(counter);
counter = counter + 1;

How can I fix this ?


Solution

  • I tried this:

    function data = generate_data(id)
    
    persistent generated_data;
    if(isempty(generated_data))
        generated_data = [0 1 2 3 4 5 6 7 8 9]; 
    end
    
    data = generated_data(mod(id - 1, length(generated_data)) + 1);
    

    In each call I can generate data set on demand using id. I have to remember that one data set can be reached only for one id. It works, but not solve my problem. I would eliminate parametr id and use internal counter like in first post.