%% Find Length of DataQueue
% When you send a message to a DataQueue object, the message waits in the queue until it is processed by a listener. Each message adds 1 to the queue length. In this example, you use the QueueLength property to find the length of a DataQueue object.
% When a MATLAB process creates a DataQueue 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 DataQueue object on the client, and send data from a worker.
% First, create a parallel pool with one worker.

parpool(1);

%
% Then, create a DataQueue.

q = parallel.pool.DataQueue

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

fprintf('On the client: %i\n', q.QueueLength)
parfor i = 1
    fprintf('On the worker: %i\n', q.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 from the worker. Then, use the QueueLength property to find the length of the queue.

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

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

%
% The QueueLength property is 1 on the client, and 0 on the worker. Create a listener to process the queue by immediately displaying the data.

el = afterEach(q, @disp);

% Wait until the queue is empty, then delete the listener.

while q.QueueLength > 0
    pause(0.1);
end
delete(el);

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

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

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