Scheduling
What is Scheduling?
     Deciding which tasks to process, for how long, and in what order is achieved
      through scheduling algorithms
     A CPU is responsible for processing tasks as fast as possible
     Different algorithms are used to prioritise and process tasks that need CPU time
     The algorithms have different uses, benefits and drawbacks.
Scheduling categories
     Preemptive: allocates the CPU for time-limited slots
     Non-preemptive: allocates the CPU to tasks for unlimited time slots
Preemptive Scheduling
     Allocates the CPU for a specific time quantum to a process
     Allows interruption of processes currently being handled
     It can result in low-priority processes being neglected if high-priority processes
      arrive frequently
     Example algorithms include Round Robin and Shortest Remaining Time First
Non-Preemptive Scheduling
     Once the CPU is allocated to a process, the process holds it until it completes
      its burst time or switches to a 'waiting' state
     A process cannot be interrupted unless it completes or its burst time is reached
     If a process with a long burst time is running, shorter processes will be neglected
     Example algorithms include First Come First Serve and Shortest Job First
Scheduling Algorithms
Round robin (RR)
     RR is a pre-emptive algorithm, equally distributing processor time amongst all
      processes
     Each process is given a time quantum to execute
     Processes that are ready to be worked on get queued
     If a process hasn’t been completed by the end of its time quantum, it will be
      moved to the back of the queue
                           Round robin scheduling algorithm
First-Come-First-Served (FCFS)
      FCFS is non-preemptive, prioritising processes that arrive at the queue first
      The process currently being worked on will block all other processes until it is
       complete
      All new tasks join the back of the queue
                    First-Come-First-Served scheduling algorithm
Shortest job first (SJF)
      SJF is non-preemptive, where all processes are continuously sorted by burst
       time from shortest to longest
      When new processes arrive on the queue, they are prioritised based on their
       burst time in the next cycle
      Shorter jobs are placed at the front of the priority queue
      Longer jobs have lower priority, so they are placed at the back
                       Shortest job first scheduling algorithm
Shortest remaining time first (SRTF)
      SRTF is a preemptive version of SJF, where processes with the shortest
       remaining time are higher priority
      Time quantum is set, and if a task doesn’t complete in time, it will be re-queued
       for further processing
      Before the next cycle starts, all processes are inspected and ordered by the
       shortest remaining time to complete
                             Memory Management
What is Memory Management?
     Memory management is a fundamental role of the operating system, dealing with
      the allocation and deallocation of the computer's primary memory
     When a user opens an application, its data is loaded from storage into active memory so
      that it can run smoothly
     When a user opens a file from the file system, e.g. word document, the CPU loads
      this file data, as well as application data, into the primary memory
     Primary memory is a limited resource in the system, so it needs careful management
     Efficient allocation of memory enables a system to continue multitasking
     Memory management is made more efficient through 3 techniques:
          o Paging
          o Segmentation
          o Virtual Memory
                          Links between different types of memory
Exam Tip
     The main benefit of memory management is to make computer systems run smoothly.
      Most users don’t realise that as they effortlessly move between applications, it’s made
      possible because the OS is rapidly reallocating memory depending on the task that the
      user is completing.
     Make sure you can name one benefit and one drawback for each memory management
      method in this revision note.
                                          Paging
What is Paging?
     Data stored in memory will lead to the smooth running of applications
     Paging is a method of chunking the primary memory into equal-sized blocks
     When an application is launched, data will be moved from the hard disk into Pages for
      faster access
     As users move between applications, memory is dynamically allocated
     Pages will be taken away from applications not in active use and granted to applications
      that are in active use
     Paging can lead to internal fragmentation
     If a 200KB file is divided into four 64KB Pages, the last Page would have 8KB of unused
      space
     Unused space in a Page is wasteful because other unrelated data cannot be stored in this
      Page
     Over time, more pockets of wasted space will exist across the memory; this process is
      called internal fragmentation
     The image below shows a single 64KB Page with 4KB of unoccupied space
     The box below this shows many Pages, each with varying sizes of internal fragments
                                   Internal fragmentation
                                    Segmentation
What is Segmentation?
     Segmentation is a method of chunking memory into blocks that correspond to
      different types of data needed by an application
     A video editing application may have a Segment for video data, audio data and special
      effects
     Segments are not all the same size; they are sized depending on their allocated data
     Segmentation is space-efficient due to only allocating space depending on the amount an
      application needs
     Segmentation can lead to external fragmentation
     As Segments fill up the memory, physical gaps reduce the maximum size of new
      Segments that can be allocated
     Below (left) shows different application data assigned to a Segment
     The arrangement of data in the segment becomes more fragmented over time because
      as blocks are taken away it's not possible to guarantee a new block will occupy the same
      amount of space
     Below (right) shows a defragmented version of the Segment to highlight the total unused
      space
                                     External fragmentation
                                     Virtual Memory
Virtual Memory
      If a computer is running low on primary memory, it can make secondary storage act as
       an 'extension' of the main memory
      The operating system can offload data from the primary memory into virtual memory
      Virtual memory creates an illusion of a larger memory and enables applications to
       continue to multitask
      However, accessing data in virtual memory is considerably slower compared to RAM
      Solid-state drives are faster than traditional hard-disk drives, but neither are as fast as
       RAM
      Over-reliance on virtual memory can lead to performance issues
   Memory
 Management          Description              Example                 Benefits           Drawbacks
  Technique
                                      A process needing    Facilitates efficient
                   Divides memory 200KB of memory is             memory                This can lead to
      Paging       into fixed-sized divided into four 64KB management and                  internal
                    blocks (pages)    pages, leaving 8KB    enables the use of          fragmentation
                                    unused in the last page virtual memory
                                    In a video editing
               Divides memory
                                   application, different
              into variable-sized                          Allows for intuitive This can result in
                                     segments may be
 Segmentation segments based on                               and efficient         external
                                  created for video data,
               logical parts of a                            memory access       fragmentation
                                  audio data, effects, and
                    process
                                       UI elements
                                     When memory-intensive                         Slower to access
                                                                Allows more
               Uses hard drive       applications exceed the                         than physical
                                                             extensive programs
                  space as an        available RAM, the OS                         memory, which
Virtual Memory                                                  to be run and
                'extension' of        moves less frequently                            degrades
                                                             facilitates effective
                    RAM               accessed pages to the                         performance if
                                                                multitasking
                                            hard disk                                  overused
Exam Tip
      Virtual memory is a method of memory management.
           o Not to be confused with Virtual Storage, which is storing files in the cloud.
Worked example
Describe how the operating system would use virtual memory to load program C when there's
not enough space in physical memory.
                                                                                             [3]
Answer that gets full marks:
The operating system can use virtual memory to act as an extension of the computer's primary
memory. This means less-critical data can be offloaded from the primary memory into virtual
storage, useful when a higher-priority set of processes require immediate attention. If the OS
offloaded data from the RAM into virtual memory, this would free up space for program C to be
loaded into RAM.
Acceptable answers you could have given instead:
Program C can be loaded into the RAM if the operating system moves files and data into virtual
memory. Virtual memory acts as an extension of the RAM.
Worked example
Imogen buys a desktop computer. It comes with an operating system installed.
Describe two ways that an operating system could manage physical memory.
                                                                                             [4]
How to answer this question
      Recall two methods of memory management (Paging, segmentation, virtual memory)
      Explain how each of these works and how they assist in memory management
Example answer that gets full marks:
Imogen's operating system could manage physical memory in two ways. Paging, which is a
method of dividing memory into fixed-size chunks known as pages. Application data can be
allocated and deallocated to pages making it a flexible system depending on the activity of the
user.
The system could also use virtual memory, a method of extending the available physical memory
by using a portion of the hard drive. This allows more programs to run simultaneously and
enhances the overall system performance.
Acceptable answers you could have given instead:
Imogen's computer uses paging to manage memory. This means it breaks down the memory into
fixed-size pieces and swaps them in and out as needed.
The computer also uses something called virtual memory. It uses part of the hard drive to act like
extra memory, so more programs can run at the same time, and everything works faster.
                  Shortest remaining time first scheduling algorithm
Comparison and Summary of Scheduling Algorithms
  Algorithm                     Benefits                               Drawbacks
                   All processes get a fair share of the
                                  CPU                      Choosing the right time quantum can
                                                                       be difficult
 Round Robin         Good for time-sharing systems
                                                         This can lead to a high turnaround time
                 Predictable, as every process gets equal and waiting time for long processes
                                   time
                                                         This can lead to poor performance if a
                     Simple and easy to understand         long process arrives before shorter
  First Come,                                                           processes
  First Served     Fair in the sense that processes are
                     served in the order they arrive      High-priority tasks wait for their turn
                                                                      in the queue
                                                           Requires knowing the burst time of
                         Minimises waiting time                   processes in advance
 Shortest Job
    First
                  Efficient and fast for short processes    Long processes can starve if short
                                                                processes keep arriving
                  Ideal for jobs that have shorter burst
                                                         Like SJF, it requires knowing the burst
                                   times
                                                              time of processes in advance
 Shortest Time
  Remaining       It is preemptive, so it can be aligned
                                                           High context switching overhead due
                  with CPU for best performance (time
                                                                      to preemption
                                quantum)
      The suitability of a scheduling algorithm largely depends on the specific scenario
       and the system requirements
      A drawback in one scenario may not be a drawback in another
Worked example
A company makes anti-virus software. When running anti-virus software, an operating
system uses a scheduling algorithm to allocate CPU time to the anti-virus software.
Explain why a First Come First Served scheduling algorithm would not be suitable in
this situation.
                                                                                                 [2]
How to answer this question:
      Think of the conditions that anti-virus software runs optimally
      Recall the way the FCFS algorithm works and its benefits and drawbacks
      Link how the optimal running of anti-virus is incompatible with FCFS scheduling
Example answer that gets full marks:
Anti-virus software is high-priority because it scans the operating system constantly,
looking for threats. When a threat is detected, anti-virus will quarantine or eliminate
them. To work effectively, anti-virus software needs high-priority access to CPU time.
Using FCFS could delay these critical tasks if many other processes are in the queue
ahead of the anti-virus software. Other less crucial tasks could get CPU time before the
anti-virus process, leading to potential security risks.
Acceptable answers you could have given instead:
The FCFS algorithm is unsuitable because essential antivirus processing would be
placed at the back of the queue and wait for its turn. Lower-priority tasks would use
valuable CPU time, meaning the system could be at risk.
                               System Interrupts
What are interrupts?
      An interrupt is a signal to the processor that stops its current task and performs
       a different task temporarily
      Interrupts can be hardware events or time-sensitive tasks
      When an interrupt occurs, the processor suspends the current
       program execution and transfers control to an interrupt service routine
Purpose and Role of Interrupts
      Real-time Event Handling: hardware errors and signals from input devices e.g.
       hard disk failure
      Device Communication: alerts from external devices e.g. printer jams and
       network errors
      Multitasking: suspending processing in one application so that the user can
       switch to another
Types of Interrupts
   Type       Definition          Example
             Generated by   Keyboard input, mouse
Hardware
               external      movements, disk I/O
Interrupts
               devices            requests
            Triggered by
                           Application requests to
 Software software or the
                           open a file, division by
Interrupts    operating
                                 zero errors
               system
            Intentionally   Software debugging,
   Trap
           triggered by a handling unexpected error
Interrupts
              program                cases
The Interrupt Process
   1. Interrupt Request (IRQ)
          o An external device or software generates an interrupt, signalling the
             processor to stop its current task
          o The interrupt controller passes this to the interrupt handler for assessment
   2. Interrupt Acknowledge
          o The interrupt handler decides if the interrupt needs to be dealt with now or
             later
          o If yes, the current contents of the processor registers are saved in
             memory
   3. Interrupt Service Routine (ISR) Lookup
          o The processor fetches the corresponding Interrupt Service Routine (ISR)
             associated with the interrupt type
   4. ISR Execution
          o The processor transfers control to the ISR and executes the routine to
             handle the specific interrupt
   5. Interrupt Exit
          o After the ISR completes, the processor restores the content of the
             registers from step 2
          o The fetch-decode-execute cycle is resumed
                                The interrupt process
What is an ISR?
      An ISR is a special function that handles a particular interrupt type
      Each type of interrupt has a corresponding routine, e.g. printer jam, hard disk
       failure, file download error, network connection error all have routines to be
       followed when they happen
      ISRs should be concise, efficient, and carefully designed to minimise the time
       taken to execute, as they often need to handle time-sensitive events
Interrupt priority and nesting
      Interrupt prioritisation means the processor can acknowledge and switch to
       resolving a higher-priority interrupt
      Prioritising interrupts is vital because many things can go wrong at the same time
      Lower-priority ISRs may be temporarily suspended until the higher-priority
       ISR completes the execution
      Nesting of interrupts refers to the ability of the processor to handle interrupts
       within interrupts
      Proper management of nested interrupts avoids potential conflicts and ensures
       system stability
                                 Nesting of interrupts
Interrupt priority handling
                        System handling of interrupt priority
What is a Device Driver?
      A device driver is a piece of software that enables communication between an
       operating system and specific hardware devices such as:
           o Printers
           o Graphics cards
           o Network cards
      Device drivers allow the OS to control and interact with those devices
      Because many external devices have embedded system software, a
       driver bridges the gap between a major operating system and a tiny hardware
       OS
      Device drivers make it possible to perform specific operations on the hardware
       e.g. a printer driver enables the OS to send print commands and manage print
       jobs
      Most hardware manufacturers write their own device driver software, meaning a
       single operating system may have several printer drivers installed
Worked example
Adding a DVD drive to a computer often requires the installation of a piece of software
called a device driver.
State the purpose of a device driver.
                                                                                        [1]
How to answer this question:
      Pick one example of a hardware device and describe what happens between it
       and the operating system
      Explain that this is made possible through device driver software
Example answer that gets full marks:
The purpose of a device driver is to enable the operating system to interact with and
control a hardware device. For example, a printer would have an associated device
driver so the OS could send or receive data from a printer system.
Acceptable answers you could have given instead:
The purpose of a device driver is to enable communication between an operating
system and external hardware.
                                Virtual Machines
What are virtual machines?
      Virtual machines (VMs) are entire operating systems running inside another
       operating system
      A user running Windows 11 could run a virtual machine of MacOS
      This would allow them to navigate the GUI of MacOS and install software on it
      Running a virtual machine helps access software that is only designed to run on
       specific operating systems
      VM management software includes a Hypervisor that monitors all activity
       happening inside the VM
Structure of several virtual machines running on a single piece of hardware
Cross-platform and forwards compatibility
     Not all software is designed to run on all operating systems
     Apple commonly makes software that only runs on MacOS for performance
      reasons
     A Windows user could run a virtual machine of MacOS and install the software
      they need
     Most software needs to be updated to work on the latest versions of operating
      systems
     A user running the latest release of Windows may need to run a virtual machine
      of a previous release of Windows to use an application that hasn't received
      a forwards-compatibility update
In software testing
     VMs are a way to create isolated test environments, that leave the host
      operating system unaffected
     Isolated environments allow a developer to:
          o Monitor the way their software affects system performance
          o Test on a clean-slate system, while no other applications are running
     VM management software can create virtual machines that act like they
      have older hardware
     This allows developers to build software that can be run on older hardware so
      that more users can use the software
     A developer can test against various operating systems, such as MacOS,
      Linux and Windows, for greater compatibility
      This is achieved through compiling into intermediate code and running against
       different operating systems
Consequences
      VMs share the same system hardware as the host OS
      Over-use of VMs can exhaust the host OS of the system of CPU, hard disk and
       memory
          o VM software such as VirtualBox can set maximum limits on system
             resources
          o A low-specification machine could be configured to allocate only 1GB of
             memory and 20% of CPU
          o A high-specification machine could afford up to 8GB of memory and
             50% of the CPU
      Operating systems are commonly free to download, but require an activation
       payment to access all features
Worked example
Explain why the programmers of anti-virus software may make use of virtual machines
when developing the updates.
                                                                                       [3]
How to answer this question:
      Recall two benefits of using virtual machines in developing software
      Link these benefits to some considerations needed when developing anti-virus
       software
Example answer that gets full marks:
Virtual machines (VMs) are essential in developing anti-virus software updates for
several reasons. VMs create an isolated environment that is separate from the host
operating system. This enables developers to safely work with virus test code that could
risk the integrity of their own operating system. VMs can also be configured to emulate
various types of hardware. This allows developers to understand how their anti-virus
software will perform on different devices and under different conditions, ensuring a
wider range of compatibility.
Acceptable answers you could have given instead:
Virtual machines create an isolated test environment from the host operating system.
This means working with harmful test code carries less risk. Virtual machine
management software can monitor the VM through the Hypervisor. This will show how
the software affects VM system performance, allowing the programmer to make
changes where needed.
                                         Stages of Compilation
What is Compilation?
       Compilation is a process that translates a program written in a high-level
        programming language into machine code
       Only machine code can be executed by a computer
       There are four stages involved in this process:
           o Lexical Analysis
           o Syntax Analysis
           o Code Generation
           o Optimisation
Lexical Analysis
       Lexical analysis means studying the words or vocabulary of a language
       This stage involves identifying lexical 'tokens' in the code
       Tokens represent small meaningful units in the programming language, such as:
             o   Keywords
                         var, const, function, for, while, if
             o   Identifiers
                     Variable names, function names
             o   Operators
                         '+', '++', '-', '*'
             o   Separators
                         ',' ';', '{', '}', '(', ')'
       During this stage, unnecessary elements like comments and whitespace are
        ignored
       For example, if the following code is being compiled:
var x = function(x,y) {
if(x>2) {
return x*y;
}
return x+y;
}
       The result of lexical analysis is a token table
                 Token              Type
      1            var            Keyword
      2             x             Identifier
      3             =             Operator
      4          function         Keyword
      5             (            Separator
      6             x             Identifier
      7             ,            Separators
      8             y             Identifier
      9             )            Separator
      10            {            Separator
      11          return          Keyword
      12            x             Identifier
      13            *             Operator
      14            y             Identifier
      15            ;            Separator
      16            }            Separator
Syntax Analysis
          Now that tokens have been identified, syntax analysis makes sure they
           all adhere to the syntax rules of the programming language
          A symbol, e.g. '$' could be a valid token but not a valid character according to
           particular programming languages
          The dollar symbol would be flagged as breaking the syntax rules
          Other syntax errors programmers commonly make include mismatched
           parentheses or missing semicolons
          If the code passes the syntax analysis, the compiler can create an Abstract
           Syntax Tree (AST)
          An AST is a graph-based representation of the code being compiled
          An AST is an efficient way to represent the code for the next step
Example abstract syntax tree
     For the same code as above, the following abstract syntax tree can be created
Code Generation
     This step takes the AST and traverses it to generate object code that can be
      executed by the computer
Optimisation
     This step modifies the code to make it more efficient without changing its
      functionality
     This is important to attempt because it reduces the memory required to run the
      code, which leads to faster execution
     A common optimisation action is removing duplicate code
        If an 'add' function is written twice in the source code, a sophisticated compiler
         will notice this and include it only once in the object code
Worked example
Imogen is writing application software for her company and is ready to compile it.
const celsius = (fahrenheit) => {
  return (5/9) * (fahrenheit-32);
}
Referring to the example above, explain what happens during Lexical Analysis.
                                                                                              [2]
How to answer this question:
        Recall the purpose of lexical analysis and what it aims to produce
        Recall the different types of tokens that can be identified in the code
        Use examples from the code block to write your answer
Answer that gets full marks:
'Lexical analysis' breaks the code into tokens, ignoring whitespace and comments.
Tokens are identified by their type:
        keyword: 'return'
        operator: '*', '-'
        identifier: celsius, fahrenheit
        delimiter: ';', '(', ')' etc
When all tokens have been identified, a token table is produced for the next step in the
compilation.
Acceptable answers you could have given instead:
The compiler will look at all the lexical tokens in the code e.g. 'fahrenheit' is an identifier,
'return' is a keyword. All the tokens are placed into a tokens table for the next step