%% Find the Length of a PollableDataQueue
% When you send a message to a PollableDataQueue object, the message waits in the queue. Each message adds 1 to the queue length. When you use poll, one message is collected from the queue. In this example, you use the QueueLength property to find the length of a PollableDataQueue object.
% When a MATLAB process creates a PollableDataQueue object, any messages that are sent to the queue are held in the memory of that process. Therefore, the QueueLength property on all other processes is 0. In this example, you create a PollableDataQueue object on the client, and send data from a worker.
% First, create a parallel pool with one worker.

parpool(1);

%
% Create a PollableDataQueue.

pdq = parallel.pool.PollableDataQueue

% A newly created PollableDataQueue has an empty queue. You can use parfor to find pdq.QueueLength on the worker. Find the queue length on the client, and the queue length on the worker.

fprintf('On the client: %i\n', pdq.QueueLength)
parfor i = 1
    fprintf('On the worker: %i\n', pdq.QueueLength)
end

% As the queue is empty, the QueueLength is 0 for both the client and the worker. Next, send a message to the queue. Then, use the QueueLength property to find the length of the queue.

% Send a message first
parfor i = 1
    send(pdq, 'A message');
end

% Find the length
fprintf('On the client: %i\n', pdq.QueueLength)
parfor i = 1
    fprintf('On the worker: %i\n', pdq.QueueLength)
end

%
% The QueueLength property is 1 on the client, and 0 on the worker. Use poll to retrieve the message from the queue.

msg = poll(pdq);
disp(msg)

% Use the QueueLength property to find the length of the queue.

fprintf('On the client: %i\n', pdq.QueueLength)

% QueueLength is 0 because the queue processing is complete.
% Copyright 2020 The MathWorks, Inc.