Sincronização e concorrência no espaço do núcleo
Gerencie dados compartilhados com segurança no núcleo usando spinlocks, mutexes e operações atômicas, reconhecendo a diferença entre contexto de interrupção e contexto de processo.
Sincronização e concorrência no espaço do núcleo é uma aula grátis de Assembly Language & x86 Low-Level Systems Programming no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Assembly Language & x86 Low-Level Systems Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Assembly Language & x86 Low-Level Systems Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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 CPUsSpinlocks
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
Aprenda Assembly com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 12
- Aulas
- 48
Perguntas Frequentes
A aula “Sincronização e concorrência no espaço do núcleo” é grátis?
Sim — o texto completo de “Sincronização e concorrência no espaço do núcleo” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Assembly Language & x86 Low-Level Systems Programming, atualize para CoddyKit PRO. O curso de Assembly Language & x86 Low-Level Systems Programming inclui 4 aulas no total.
O que vou aprender em “Sincronização e concorrência no espaço do núcleo”?
Gerencie dados compartilhados com segurança no núcleo usando spinlocks, mutexes e operações atômicas, reconhecendo a diferença entre contexto de interrupção e contexto de processo. Você pratica Assembly Language & x86 Low-Level Systems Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Assembly Language & x86 Low-Level Systems Programming?
Nenhuma experiência prévia é necessária. Assembly Language & x86 Low-Level Systems Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Sincronização e concorrência no espaço do núcleo”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Assembly Language & x86 Low-Level Systems Programming?
Sim. Cada aula de Assembly Language & x86 Low-Level Systems Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Introdução ao Espaço do Núcleo
- Escrevendo Drivers de Dispositivo Simples
- Interação Direta com o Hardware
- Sincronização e concorrência no espaço do núcleo