function randomInit( idx )
%randomInit - initialize the random state for a task
%
%   Set each worker to use an even numbered stream based on its index. We
%   use the Threefry random number generator since the streams it
%   provides are statistically independent and are evenly distributed in
%   the state-space.

%  Copyright 2006-2018 The MathWorks, Inc.

% Since we allow adding tasks to a running job, it is impossible to set
% NumStreams to the total number of tasks in a job. We therefore use 2^32
% (approx 4.3e+9) as a reasonable upper bound. This corresponds to 100
% computers running 1 task per second for 1 year.
maxStreamIdx = 2^32;
generatorName = "Threefry4x64_20";

% Set the default random number generator for the CPU. Even numbered
% streams are used on the CPU, odd numbered ones on the GPU.
streamIdx = 2*idx;
stream = RandStream.create( generatorName, ...
    "NumStreams", maxStreamIdx, ...
    "StreamIndices", streamIdx );
RandStream.setGlobalStream(stream);

% Set the GPU random state just in case we need it (note that this doesn't
% cause the GPU libraries to load, so is cheap).
streamIdx = 2*idx + 1;
stream = parallel.gpu.RandStream.create( generatorName, ...
    "NumStreams", maxStreamIdx, ...
    "StreamIndices", streamIdx );
parallel.gpu.RandStream.setGlobalStream( stream );
