Lock

XWOS locks

Critical Section Management

A critical section refers to a code fragment that accesses shared resources. In traditional RTOS, the following methods are commonly used to protect critical section resources:

  • Using cooperative kernel: threads (tasks) that do not voluntarily yield the CPU will not trigger a schedule, so shared resources accessed within threads (tasks) are safe.
  • Disabling preemption: can be used to protect resources shared by multiple threads (tasks).
  • Disabling interrupt (IRQ): can be used to protect resources shared between threads and between threads and interrupts.
  • Mutex: can be used to protect resources shared by multiple threads (tasks).

The XWOS kernel is designed for MP systems (UP can be viewed as a special case of MP), so the approach to entering a critical section differs somewhat from traditional RTOS:

  • Disable preemption: use the lock and unlock forms of the API from spinlock or its derived locks;
  • Disable all CPU interrupt (IRQ): use the lock_cpuirq and unlock_cpuirq forms of the API from spinlock or its derived locks. If accessing a critical section requires acquiring multiple spinlocks or their derived locks, use the lock_cpuirqsv and unlock_cpuirqrs forms of the API to save and restore the CPU interrupt enable flag, preventing the inner lock from accidentally re-enabling CPU interrupts upon unlock;
  • Disable partial interrupts (IRQ): use the lock_irqs and unlock_irqs forms of the API from spinlock or its derived locks. If accessing a critical section requires acquiring multiple spinlocks or their derived locks, use the lock_irqssv and unlock_irqsrs forms of the API to save and restore partial interrupt enable flags, preventing the inner lock from accidentally re-enabling these interrupts upon unlock;
  • Disable bottom half (BH): use the lock_bh and unlock_bh forms of the API from spinlock or its derived locks;
  • Mutex: can only be used to protect resources shared by multiple threads;
  • Atomic operations: XWOS provides the atomic operation function library xwos/lib/xwaop.h, and abstracts a memory model similar to std:atomic.

Spinlock

XWOS spinlock

Seqlock

XWOS seqlock

Mutex

XWOS mutex