What is the difference between a tasklet, a workqueue and a threaded IRQ?
Short answer: A tasklet runs in softirq context: soon after the interrupt, on the same CPU, but it cannot sleep, and tasklets are deprecated for new code. A workqueue item runs in a kernel thread (kworker) in process context, so it can sleep, at the cost of more scheduling latency. A threaded IRQ gives each interrupt its own kernel thread (irq/NN-name) with real-time priority; it can sleep and is the standard choice for devices on slow buses like I2C and SPI.
| Tasklet / softirq | Workqueue | Threaded IRQ | |
|---|---|---|---|
| Context | softirq (atomic) | process (kworker thread) | process (dedicated irq thread) |
| Can sleep | no | yes | yes |
| Latency | low | higher (normal priority, shared workers) | low, SCHED_FIFO priority |
| Concurrency | a given tasklet never runs on two CPUs at once | configurable (ordered, unbound, per-CPU) | one thread per IRQ |
| Typical use | legacy fast deferral | slow or delayed work, firmware loading, retries | I2C/SPI devices, GPIO interrupts, most new drivers |
| Status | deprecated (use BH workqueues) | current | current |
Threaded IRQ for an I2C device
static irqreturn_t sensor_thread(int irq, void *data)
{
struct mysensor *s = data;
unsigned int status;
if (regmap_read(s->map, REG_STATUS, &status)) /* sleeps: OK in the thread */
return IRQ_NONE;
if (!(status & DATA_READY))
return IRQ_NONE;
read_sample_and_push(s);
return IRQ_HANDLED;
}
ret = devm_request_threaded_irq(dev, client->irq, NULL, sensor_thread,
IRQF_ONESHOT, "mysensor", s);
With no primary handler and IRQF_ONESHOT, the core masks the line until the thread finishes, which is required for level-triggered interrupts that can only be cleared by an I2C read.
Workqueue example
INIT_WORK(&d->work, mydev_work_fn); /* in probe */
schedule_work(&d->work); /* from the IRQ handler */
cancel_work_sync(&d->work); /* in remove: wait for it to finish */
Follow-up: with PREEMPT_RT, all interrupt handlers are forced into threads (except those marked IRQF_NO_THREAD), and softirqs run in thread context too.