Skip to content

Wait Queue

Overview

Wait queues provide condition-based sleeping and wake-up mechanisms in the Linux kernel.

Instead of repeatedly polling a condition, a task can sleep until another execution context signals that the condition has changed.

Wait queues are one of the fundamental synchronization mechanisms used throughout the Linux kernel.

Common use cases include:

  • Driver event notification
  • Producer-consumer workflows
  • Event-driven state machines
  • Blocking I/O
  • Thread synchronization

Why Wait Queues Exist

Without wait queues, a task must continuously poll:

while (!condition)
    cpu_relax();

This wastes CPU resources.

With wait queues:

wait_event(wq, condition);

The task sleeps until the condition becomes true.


Wait Queue Architecture

A wait queue consists of:

wait_queue_head_t
Waiting Tasks
Wake-up Event

Typical flow:

wait_event()
sleep
wake_up()
re-evaluate condition
continue

Condition-Based Waiting

Unlike completion, wait queues do not represent an operation.

Wait queues represent a condition.

Example:

wait_event(
        wq,
        data_available);

The task waits until:

data_available == true

Event-Driven State Machines

Wait queues are commonly used to build event-driven kernel threads.

Example:

while (!kthread_should_stop()) {

    wait_event(
            wq,
            event_pending ||
            kthread_should_stop());

    process_event();
}

This pattern avoids polling loops and minimizes CPU usage.


Wait Queue vs Polling

Polling:

while (!event)
    msleep(100);

Problems:

  • Wasted wakeups
  • Increased latency
  • Unnecessary CPU usage

Wait queue:

wait_event(wq, event);

Benefits:

  • Event-driven execution
  • Lower CPU usage
  • Immediate response

Wait Queue vs Completion

Feature Wait Queue Completion
Waiting Model Condition-based Operation-based
Repeated Events Excellent Limited
State Machine Excellent Poor
One-shot Synchronization Possible Excellent
Multiple Conditions Supported Not supported

Typical Driver Usage

Wait queues are commonly used in:

  • Character drivers
  • Blocking read operations
  • Worker threads
  • Event loops
  • State machines

Example:

read()
wait_event()
data available
copy_to_user()

Relationship to Other Synchronization Mechanisms

Wait queues are often combined with:

  • Mutex
  • Spinlock
  • Atomic variables
  • Kernel threads

Many higher-level synchronization mechanisms are built on top of wait queues.

Completion is one example.


Summary

Wait queues provide condition-based sleeping and wake-up functionality.

They are best suited for:

  • Event-driven processing
  • State machines
  • Blocking I/O
  • Repeated event handling

When the goal is to wait for a condition to become true, wait queues are usually the preferred kernel synchronization primitive.