中断屏蔽
//现场保存恢复
unsigned long flags;
local_irq_save(flags)
……
……
local_irq_restore(flags)
//屏蔽(cpu中断)
local_irq_disable()
……
……
local_irq_restore(flags)
local_irq_enable()
//屏蔽底半部(软中断)
local_bh_disable()
local_bh_enable()
原子操作
//cpu指令层面保证操作不会并发
typedef struct {
int counter;
} atomic_t;
atomic_t test_atomic_value;
atomic_set(atomic_t *v, int i);
atomic_read(atomic_t *v);
atomic_inc(atomic_t *v);
atomic_dec(atomic_t *v);
…………
自旋锁
(适用于单核或者多核内核可抢占的情况)
typedef struct spinlock {
union {
struct raw_spinlock rlock;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
# define LOCK_PADSIZE (offsetof(struct raw_spinlock, dep_map))
struct {
u8 __padding[LOCK_PADSIZE];
struct lockdep_map dep_map;
};
#endif
};
} spinlock_t;
spinlock_t lock;
spin_lock_init(&lock);
spin_lock(&lock);
……
……
spin_unlock(&lock);
信号量
(会引起休眠,不能在中断上下文使用)—自旋锁+队列
struct semaphore {
raw_spinlock_t lock;
unsigned int count;
struct list_head wait_list;
};
struct semaphore sem;
void sema_init(&sem, int val);
down(&sem);
up(&sem);
……
……
互斥体
(原子变量,自旋锁,队列)
struct mutex {
/* 1: unlocked, 0: locked, negative: locked, possible waiters */
atomic_t count;
spinlock_t wait_lock;
struct list_head wait_list;
#if defined(CONFIG_DEBUG_MUTEXES) || defined(CONFIG_MUTEX_SPIN_ON_OWNER)
struct task_struct *owner;
#endif
#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
struct optimistic_spin_queue osq; /* Spinner MCS lock */
#endif
#ifdef CONFIG_DEBUG_MUTEXES
void *magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map dep_map;
#endif
};
struct mutex lock;
mutex_init(&lock);
mutex_lock(&lock);
mutex_unlock(&lock);