0Pricing
Assembly Language & x86 Low-Level Systems Programming · Lección

Sincronización y concurrencia en el espacio del kernel

Gestione los datos compartidos de forma segura en el kernel mediante spinlocks, mutexes y operaciones atómicas, teniendo en cuenta la diferencia entre el contexto de interrupción y el contexto de proceso.

Sincronización y concurrencia en el espacio del kernel es una lección gratuita de Assembly Language & x86 Low-Level Systems Programming en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Assembly Language & x86 Low-Level Systems Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Assembly Language & x86 Low-Level Systems Programming incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The Concurrency Problem

Kernel code runs in a brutally concurrent environment: multiple CPUs, preemptible threads, and interrupts that fire anytime. Unprotected shared data leads to race conditions and corruption.

Process vs Interrupt Context

Kernel code runs in two contexts:

  • Process context: on behalf of a syscall; can sleep
  • Interrupt context: handling hardware; must NOT sleep

The context dictates which locking primitive is legal.

Atomic Operations

The simplest protection is an atomic operation that completes in a single uninterruptible step. The kernel offers types like atomic_t with helpers that map to lock-prefixed x86 instructions.

atomic_t counter = ATOMIC_INIT(0);
atomic_inc(&counter);
int v = atomic_read(&counter);

How Atomics Work in Hardware

On x86 the lock prefix makes a read-modify-write instruction atomic across cores by asserting a cache-line lock.

lock inc dword [counter]   ; atomic increment across CPUs

Spinlocks

A spinlock busy-waits until the lock is free. It never sleeps, so it is the only choice in interrupt context. Hold it for the shortest time possible — spinning wastes CPU.

spinlock_t lock;
spin_lock(&lock);
// critical section
spin_unlock(&lock);

Spinlocks and Interrupts

If an interrupt handler tries to take a spinlock already held on the same CPU, you deadlock. Use spin_lock_irqsave to disable local interrupts while holding the lock.

unsigned long flags;
spin_lock_irqsave(&lock, flags);
// safe even against IRQs
spin_unlock_irqrestore(&lock, flags);

Mutexes and Semaphores

A mutex puts the waiting thread to sleep instead of spinning. It is efficient for longer critical sections but is only usable in process context, never in an interrupt handler.

struct mutex m;
mutex_init(&m);
mutex_lock(&m);
// may sleep here
mutex_unlock(&m);

Choosing the Right Primitive

Quick decision guide:

  • Short, may run in IRQ context -> spinlock
  • Long, process context, can sleep -> mutex
  • Single counter or flag -> atomic

Read-Copy-Update (RCU)

RCU allows lock-free reads of shared data while writers create a new copy and swap a pointer. Readers see either the old or new version, never a torn one. It scales superbly for read-mostly structures.

Memory Barriers

Compilers and CPUs reorder memory accesses. A memory barrier (smp_mb(), smp_wmb()) forces ordering so other cores observe writes in the intended sequence — vital for lock-free code.

Deadlock Avoidance

To prevent deadlock: always acquire multiple locks in a fixed global order, keep critical sections tiny, and never call a sleeping function while holding a spinlock or interrupts are disabled.

Quick Check

Test your kernel concurrency knowledge.

Recap

You learned kernel synchronization:

  • Atomics protect single values via lock-prefixed instructions
  • Spinlocks busy-wait and work in IRQ context; use irqsave variants
  • Mutexes sleep and are process-context only
  • RCU and memory barriers enable scalable lock-free reads

Preguntas frecuentes

¿La lección «Sincronización y concurrencia en el espacio del kernel» es gratis?

Sí — el texto completo de «Sincronización y concurrencia en el espacio del kernel» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Assembly Language & x86 Low-Level Systems Programming, actualiza a CoddyKit PRO. El curso de Assembly Language & x86 Low-Level Systems Programming incluye 4 lecciones en total.

¿Qué aprenderé en «Sincronización y concurrencia en el espacio del kernel»?

Gestione los datos compartidos de forma segura en el kernel mediante spinlocks, mutexes y operaciones atómicas, teniendo en cuenta la diferencia entre el contexto de interrupción y el contexto de pro… Practicas Assembly Language & x86 Low-Level Systems Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Assembly Language & x86 Low-Level Systems Programming?

No se requiere experiencia previa. Assembly Language & x86 Low-Level Systems Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Sincronización y concurrencia en el espacio del kernel»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Assembly Language & x86 Low-Level Systems Programming?

Sí. Cada lección de Assembly Language & x86 Low-Level Systems Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción al espacio del kernel
  2. Escritura de controladores de dispositivos sencillos
  3. Interacción directa con el hardware
  4. Sincronización y concurrencia en el espacio del kernel
← Volver a Assembly Language & x86 Low-Level Systems Programming