同步互斥小结

中断屏蔽

	//现场保存恢复
	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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值