Workqueue API Reference¶
Overview¶
Workqueues provide deferred execution by moving work from atomic contexts such as interrupt handlers into sleepable process contexts.
Work handlers execute in kernel worker threads (kworker) and may perform operations that are not allowed in Hard IRQ Context.
Common use cases:
- Deferred interrupt processing
- Retry mechanisms
- Device recovery
- Debounce handling
- Delayed execution
- Background jobs
Core Data Structures¶
struct work_struct¶
Represents a work item executed by a workqueue.
Example:
struct delayed_work¶
Represents delayed execution using:
Example:
Work Initialization¶
INIT_WORK()¶
Initialize a work item.
Prototype:
Example:
INIT_DELAYED_WORK()¶
Initialize delayed work.
Prototype:
Example:
Work Submission¶
schedule_work()¶
Queue work to the default global workqueue.
Prototype:
Example:
Equivalent:
queue_work()¶
Queue work to a specific workqueue.
Prototype:
Example:
Delayed Work Submission¶
schedule_delayed_work()¶
Schedule delayed execution.
Prototype:
Example:
mod_delayed_work()¶
Modify or reschedule delayed work.
Prototype:
bool mod_delayed_work(
struct workqueue_struct *wq,
struct delayed_work *dwork,
unsigned long delay);
Example:
Typical use cases:
- Debounce
- Retry timeout
- Monitoring timer refresh
Workqueue Creation¶
alloc_workqueue()¶
Create a private workqueue.
Prototype:
struct workqueue_struct *
alloc_workqueue(
const char *fmt,
unsigned int flags,
int max_active,
...);
Example:
alloc_ordered_workqueue()¶
Create a workqueue that executes work items sequentially.
Prototype:
Example:
Workqueue Cleanup¶
cancel_work_sync()¶
Cancel pending work and wait for running work to finish.
Prototype:
Example:
Notes:
cancel_delayed_work_sync()¶
Cancel delayed work and wait for completion.
Prototype:
Example:
flush_workqueue()¶
Wait until all queued work items finish.
Prototype:
Example:
Notes:
destroy_workqueue()¶
Destroy a private workqueue.
Prototype:
Example:
Notes:
Common Pitfalls¶
Scheduling The Same Work Multiple Times¶
The same work item may only be pending once.
Example:
Result:
Calling Sync APIs From IRQ Context¶
Invalid:
inside:
Reason:
Forgetting Cleanup During Driver Removal¶
Incorrect:
Correct:
Driver Removal Pattern¶
Recommended sequence:
disable_irq()
↓
cancel_work_sync()
↓
cancel_delayed_work_sync()
↓
destroy_workqueue()
↓
free_irq()
↓
release resources
Related APIs¶
- request_threaded_irq()
- disable_irq()
- enable_irq()
- mutex_lock()
- wait_event()
- kthread_run()
Related Labs¶
- Day35 - IIO IRQ Trigger Driver
- Day50 - Pollable Character Driver
- Day67 - Workqueue Fundamentals
Related Notes¶
- Workqueue and Deferred Execution