IB COMPUTER SCIENCE | A1.3.4 Polling and Interrupt Handling

Lesson objective

Evaluate polling and interrupt handling using event frequency, CPU overhead, power, predictability, latency and security, reaching justified conclusions for real situations.

Learn

A1.3.4 | POLLING AND INTERRUPT HANDLING

01 | HOW DOES THE CPU KNOW SOMETHING HAPPENED?

A key is pressed, a storage read finishes, or a packet arrives at a network adapter. The CPU may be running other instructions at that moment. How does the system discover that an event needs attention?

Two approaches are polling, where software checks a device or status repeatedly, and interrupt-driven handling, where an event can trigger a request for CPU attention. Both still require software to interpret the device state and do useful work.

Neither approach is always best. You must evaluate event frequency, processing overhead, battery or mains power, predictability, latency requirements and security. The right conclusion depends on the situation.

We will distinguish detecting an event, starting a handler and completing the requested work. Those are related stages, but they do not all happen at the same instant.

02 | POLLING: CHECK, THEN CHECK AGAIN

In polling, software reads a status value to discover whether a device is ready or an event is pending. For example, it may ask a sensor whether a new measurement is available, then check again later.

Busy polling checks repeatedly in a tight loop. It can minimise the gap between checks, but occupies CPU time even when nothing has happened. A periodic polling task instead checks at scheduled intervals, leaving opportunities for other work or sleep between checks.

A polling interval is the time between checks. A short interval usually reduces detection delay but increases the number of checks. A long interval reduces checking work but can leave an event unnoticed for longer.

Polling does not necessarily freeze the whole computer. Whether other work can proceed depends on how the polling task is scheduled, whether it yields or sleeps, and how many cores are available.

03 | READ A POLLING TIMELINE

Suppose checks occur at 0, 10, 20 and 30 milliseconds. An event becomes pending at time 13 and remains recorded until checked. The check at 10 is too early; the check at 20 detects it. Detection delay is 20 − 13 = 7 ms.

An event just after a check can wait almost a full interval. If checks reliably occur every P units and the event remains pending, the detection delay is from 0 up to approximately P. With uniformly distributed event times, the mean detection delay is approximately P/2.

Those statements concern detection under the stated assumptions. If a polling task is delayed by other work, checks may not meet the intended schedule. Completing the handling also takes time.

0102030 msCheckCheckDetectCheckEvent at 13Delay = 7 ms
The event remains pending until the next check. The horizontal axis shows time, not CPU work.

04 | INTERRUPTS: REQUEST ATTENTION WHEN NEEDED

A hardware interrupt is a request generated by a device or controller to signal that an event needs attention. An interrupt controller may prioritise and deliver requests to the processor.

When an interrupt can be accepted, the processor preserves the state needed to resume the interrupted execution and transfers control to appropriate handling code. The exact entry sequence depends on the hardware and OS.

An interrupt service routine (ISR), or interrupt handler, identifies and handles the immediate cause. It may record information and arrange further work rather than completing a long operation inside the immediate handler.

The event is acknowledged or its source dealt with according to the device’s rules, so a persistent request does not keep being handled unnecessarily. On return, saved state is restored as required. The OS may resume the previous work or schedule another runnable task.

An interrupt is not the same as an error: normal input and completion events use interrupts. It is also not automatically a switch to a different application process.

05 | STEP THROUGH INTERRUPT HANDLING

Use this simplified sequence to follow a storage-read completion event. Notice that a request can be pending before a handler starts, and that further processing may run later.

06 | LATENCY IS NOT ZERO

Interrupt latency commonly means the time from an interrupt request to the start of its handler. It is different from the total time needed to finish handling the event or make an application respond.

An interrupt may wait because higher-priority work is being handled, interrupts are temporarily masked, or the processor and OS need time to enter the handler. Handling itself consumes CPU time as well.

Masking temporarily prevents selected maskable interrupts from being accepted. A request may remain pending, but that depends on the controller and device. Do not assume every event is safely remembered forever.

For sparse unpredictable events, interrupts often avoid the long wait until the next periodic poll. However, a tightly controlled polling loop can have lower or more predictable detection delay than some interrupt arrangements. Always define the required timing and the implementation assumptions.

07 | CPU OVERHEAD CHANGES WITH EVENT FREQUENCY

Polling pays a checking cost even when a check finds no work. Interrupt-driven handling pays entry, handling and return costs when interrupts occur. Both also pay the cost of processing the actual data or event.

With rare events, many polling checks may be empty, making interrupts attractive. With very frequent events, repeated interrupt entry and exit can consume substantial CPU time and disrupt other work. Processing several pending items during one poll or one interrupt can reduce per-item overhead.

An interrupt storm is a flood of interrupt activity that can make the system spend excessive time reacting instead of progressing other tasks. It may result from heavy legitimate load, faulty hardware or malicious activity.

Do not compare an empty poll’s cost with a complete interrupt handler and forget that polling must also process detected data. Separate detection overhead from useful service work, and state whether batching is possible.

08 | EXPLORE DETECTION DELAY AND CPU COST

Choose an event pattern and polling interval. Both models receive the same events. Compare the per-event detection delays with the separate CPU-cost totals.

The observation window is 0 to 40 time units. Polls occur at 0 and every interval through 40. Events are queued until the next poll, so none are lost and several can be collected by one check. Interrupt handling begins one unit after each event.

For illustration, each poll costs 0.2 CPU units, each interrupt costs 0.4 entry/exit units, and each event needs 0.1 service units in either approach. These are invented constants, not measured hardware performance.

Timestamp calculations ignore queueing, blocking and interference; the CPU-cost tally does not move the displayed check or handler times. The model compares assumptions, not a full real-time simulation or an energy measurement.

Same events, different detection arrangements
Event timeNext pollPolling delayHandler startInterrupt latency
Separate cost comparison over the 40-unit window
MeasurePollingInterrupts

09 | POWER SOURCE AND SLEEP OPPORTUNITIES

A battery-powered sensor may spend most of its life waiting. If suitable hardware can wake it on an event, interrupts can allow long low-power periods instead of repeated busy checks. That can extend battery life.

Periodic polling can also sleep between checks, although waking up frequently has a cost. The result depends on polling frequency, device power states and the energy needed to wake and handle events.

Mains power reduces the importance of battery life, but CPU use, heat and energy costs still matter. A mains-powered server may choose busy polling on selected cores to reduce latency while accepting higher resource consumption.

Do not infer a battery-life figure from the simulator’s CPU-cost totals. Energy depends on hardware, sleep states, wakeups and the rest of the workload.

10 | PREDICTABILITY, CONTROLLED LATENCY AND MISSED EVENTS

A regularly sampled control variable can suit timed polling: the software knows when readings will be taken and can include that work in a schedule. The checks must reliably meet their timing, and the interval must suit the system’s requirements.

An urgent unpredictable event can suit interrupts, provided interrupt priorities, masking and handler execution allow an adequate response bound. An interrupt alone does not guarantee a hard real-time deadline.

If a signal briefly becomes active at time 2 and returns inactive at 4, checks at 0 and 5 miss it if software reads only the current level. A latched flag or event buffer can preserve evidence until checked. Buffer capacity and event-clearing rules matter.

An interrupt system can also lose or combine events if hardware, controller or buffers do not retain them adequately. Detection method and event storage are separate design decisions.

For a safety-critical deadline, evaluate worst-case end-to-end time, including detection, waiting, processing and action. A good average latency does not prove every deadline will be met.

11 | SECURITY AND SYSTEM STABILITY

A device or traffic source that creates excessive events can consume processing resources. Interrupt-driven systems need robust handling and may use rate controls, batching, masking and limits on immediate work to protect responsiveness.

Polling can limit how much work is attempted per scheduled visit, but it is not automatically secure. Malicious or faulty device data still needs validation, and queued data can overwhelm buffers if arrival exceeds service capacity.

Interrupt handlers may run with high privileges or in constrained contexts, depending on the system. Keeping immediate work short and using appropriate validation and synchronisation reduces the impact of bugs. Long work can often be deferred to a safer processing context.

Temporarily disabling notifications can help manage a flood, but doing so carelessly can delay important work or lose events. Security evaluation therefore includes both denial-of-service risk and the consequences of the mitigation.

12 | HYBRID DESIGNS COMBINE THE ADVANTAGES

A network adapter may use an interrupt to announce incoming work, then software polls a receive queue to process several packets while the queue is busy. Interrupt notifications can be re-enabled when polling finds that the queued work has been drained.

This avoids treating every packet as a separate expensive notification while still allowing event-driven behaviour during quiet periods. Real implementations have budgets, priorities and platform-specific details.

Linux networking’s NAPI is an example of combining interrupt notification and polling. It illustrates why a real system need not choose one method exclusively.

Interrupt moderation or coalescing can group notifications to reduce overhead, often at the cost of extra delay before some events are reported. State that tradeoff rather than presenting batching as free.

Further reading: interrupt notification and polling in Linux NAPI

13 | EVALUATE REAL SITUATIONS

SituationA defensible approachWhat must be evaluated
Occasional keyboard or mouse inputEvent-driven notification in the relevant software layerSparse unpredictable events; responsiveness; input stacks may also contain periodic device transfers
Network adapter under heavy trafficHybrid notification and budgeted pollingPer-packet overhead, batching delay, load and buffer capacity
Long storage read with other work availableCompletion interrupt or another event-driven completion pathAvoid repeated checks; completion latency and queued requests
Battery-powered device waiting for a buttonWake-capable interrupt where supportedSleep and wake energy, spurious events and debounce
Regularly sampled embedded sensorTimed polling or timer-triggered samplingRequired sample period, reliable schedule and short-lived signals
Real-time control systemA design with a proven suitable timing boundWorst-case detection and handling time, priorities, interference and safety requirements

A keyboard example at OS level does not prove every keyboard link is electrically interrupt-driven. For example, a USB host can schedule periodic transfers while the OS still receives event notifications through its driver stack. Choose the layer you are discussing.

14 | BUILD A CONTEXTUAL JUDGEMENT

Select a scenario and read the evaluation prompt. Form your own conclusion first, then reveal a model judgement. A good evaluation weighs a benefit against a limitation and states the conditions under which the recommendation holds.

15 | COMPARE BEFORE YOU EVALUATE

CriterionPollingInterrupt-driven handling
Event frequencyRepeated checks can be wasteful when quiet; batching may help under loadSparse events avoid empty checks; frequent notifications add overhead
Detection timingDepends on actual gaps between checksDepends on request delivery, priority, masking and handler entry
CPU costChecking plus service work; busy loops can occupy a coreEntry/exit plus service work; storms can disrupt progress
PowerBusy polling often uses more energy; periodic polling can sleepMay allow event-driven sleep/wake when supported
PredictabilityScheduled checks can support a controlled timing planPriorities can help urgent events, but interference and masking must be bounded
SecurityNeeds validation, bounded work and adequate bufferingNeeds robust handlers and protection against event floods

These are tendencies, not absolute guarantees. Polling can be appropriate for low latency, and interrupt-driven handling can be too costly under sustained load.

16 | WRITE AN EVALUATION, NOT JUST TWO DEFINITIONS

For evaluate, use the context to judge suitability. Identify the important requirements, explain benefits and limitations, then reach a supported conclusion. Use event frequency, CPU overhead, power, predictability, latency and security as relevant criteria.

For example: “For a battery sensor with rare unpredictable events, wake-capable interrupts are preferable because they can avoid repeated empty checks and permit sleep. However, spurious events and wake costs must be controlled, and the handling path must meet the response requirement. Periodic polling would be more suitable if scheduled sampling were required and its delay were acceptable.”

Avoid claims that interrupts are instant, polling always blocks all work, or either method guarantees no event loss. State the assumptions about pending flags, buffers, timing and workload.

The next lesson is HL content on multitasking and resource allocation. This lesson’s core decision is whether the detection and handling strategy fits the actual operating conditions.

Further reading: Polling and interrupt basics · Understanding interrupt latency

MATCH THE EVENT-HANDLING TERM TO ITS MEANING

Terminology

Terminology

Polling

Software checking a device or status to find pending work.

Busy polling

Repeated checks in a tight active loop.

Periodic polling

Checking at scheduled intervals.

Polling interval

The time between status checks.

Hardware interrupt

A device or controller request for processor attention.

Interrupt controller

Hardware managing delivery and prioritisation of interrupt requests.

Interrupt handler

Code responding to an accepted interrupt.

ISR

Interrupt service routine; another name for an interrupt handler.

Pending event

An event recorded as awaiting attention.

Interrupt latency

Delay from an interrupt request to the start of its handler.

Detection delay

Time from an event to its discovery by the chosen mechanism.

End-to-end latency

Time from the event through to the required completed response.

Masking

Temporarily preventing selected maskable interrupts from being accepted.

Acknowledgement

Indicating receipt or handling according to the device/controller protocol.

Execution state

Information needed to resume interrupted execution.

Overhead

Resource use for management rather than the main useful service work.

Interrupt storm

Excessive interrupt activity that can disrupt system progress.

Deferred work

Processing arranged for later outside the immediate handler.

Latched flag

An event indicator retained until it is appropriately cleared.

Event buffer

Storage holding event data until it can be processed.

Batching

Processing several pending items together.

Interrupt coalescing

Grouping notifications to reduce their frequency.

Hybrid handling

Combining event notification with polling or other strategies.

Sleep state

A lower-power state from which a system can be woken.

Wakeup

A transition allowing a sleeping component to resume activity.

Predictability

How reliably timing or event behaviour can be anticipated.

Worst-case latency

The largest response delay under stated assumptions.

Real-time requirement

A requirement that correct action occurs within a specified time constraint.

Denial of service

Preventing useful access or progress by exhausting or disrupting resources.

Evaluate

Weigh relevant evidence and tradeoffs to reach a supported judgement.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe polling correctly?
2. Checks occur at 0,10,20 ms. A latched event occurs at 13. What is detection delay?
3. Which describe interrupts correctly?
4. Which can increase interrupt latency?
5. Why can interrupts suit rare events?
6. Why might polling or a hybrid help under heavy traffic?
7. Which statements about short-lived signals are correct?
8. Which are valid security concerns?
9. Which are needed to assess a hard deadline?
10. Which make a strong evaluation?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Describe polling and distinguish periodic polling from busy polling.

2. Calculate detection delay for an event at 23 ms with checks at 0,10,20,30 ms.

3. Describe a simplified interrupt-handling sequence.

4. Explain why interrupt latency differs from total response time.

5. Evaluate interrupts for a battery device waiting for rare events.

6. Evaluate a busy loop for an occasional keyboard event.

7. Evaluate polling or hybrid handling for a heavily loaded network adapter.

8. Explain how polling can miss a short pulse.

9. Evaluate polling for a regularly sampled embedded sensor.

10. Evaluate the claim that interrupts guarantee real-time deadlines.

11. Discuss security concerns for both approaches and reach a judgement.

12. Evaluate combining interrupts with polling.

EVALUATE IT | A REMOTE MONITORING STATION

A remote battery-powered station samples temperature every minute, must respond to an unpredictable alarm input, and uploads bursts of stored readings when a link is available. Evaluate a detection strategy for each activity. Discuss CPU overhead, sleep opportunities, worst-case latency, event retention and excessive-event attacks. Reach a justified conclusion and identify assumptions that would need testing.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for A1.3.4 Polling and Interrupt Handling is coming soon. Complete the matching task and written questions in your exercise book.