%% Task Prioritization in an Operating System

% Copyright 2008-2011 The MathWorks, Inc.

%% Description
% This example shows how to schedule and execute tasks with
% different priorities.
%
% Task tokens with two priority levels are generated by the two token
% generators. Each token has attributes representing the priority and the
% task execution time. The tokens are sorted according to ascending
% priority in the Priority-Based Task Queue just before the CPU. The tokens
% are then passed to the CPU for task execution.

modelname = 'sedemo_rtos_two_priorities';
open_system(modelname);
set_param([modelname '/Task Queue Length'],'OpenScopeAtSimStart', 'off' );
set_param([modelname '/Queuing Time Plots/Queuing Delay for High Priority Tasks'],'OpenScopeAtSimStart', 'off' );
set_param([modelname '/Queuing Time Plots/Queuing Delay for Low Priority Tasks'],'OpenScopeAtSimStart', 'off' );

%% Results and Displays
% The simulation results can be seen on the following scopes:
%
% *  Priority value for tasks being served in the CPU

sim(modelname);

%%
%
% *  Queue length of the Priority-Based Task Queue
%

des.scope.CallbackSupport('CloseFig',[modelname '/Priority Scope']);
set_param([modelname '/Priority Scope'],'OpenScopeAtSimStart', 'off' );
set_param([modelname '/Task Queue Length'],'OpenScopeAtSimStart', 'on' );
sim(modelname);

%%
%
% *  Queuing delay for low-priority tasks completed
%
des.scope.CallbackSupport('CloseFig',[modelname '/Task Queue Length']);
set_param([modelname '/Task Queue Length'],'OpenScopeAtSimStart', 'off' );
set_param([modelname '/Queuing Time Plots/Queuing Delay for Low Priority Tasks'],'OpenScopeAtSimStart', 'on' );
sim(modelname);

%%
% *  Queuing delay for high-priority tasks completed
%
des.scope.CallbackSupport('CloseFig',[modelname '/Queuing Time Plots/Queuing Delay for Low Priority Tasks']);
set_param([modelname '/Queuing Time Plots/Queuing Delay for Low Priority Tasks'],'OpenScopeAtSimStart', 'off' );
set_param([modelname '/Queuing Time Plots/Queuing Delay for High Priority Tasks'],'OpenScopeAtSimStart', 'on' );
sim(modelname);

%%
% The plot with priority value for the current task indicates when a
% low-priority task was preempted by a high-priority task. The queue length
% plot displays the number of tasks queued to be processed. The queuing
% delay plots indicate that the high-priority task tokens do not experience
% any queuing delay. The low-priority task tokens experience queuing delays
% because of the preemption behavior.

%% Related Examples
% * <matlab:showdemo('sedemo_rtos_dependent_tasks'); Task Scheduling in an Operating System>
% * <matlab:showdemo('sedemo_rtos_application'); Task Preemption in an Operating System>


%% 
%cleanup
bdclose(modelname);
clear modelname;
displayEndOfDemoMessage(mfilename)
