Mutex就是资源数目为1的Semaphore

在 PV 原语中的资源数目 s,

信号量 Semaphore 就是 Linux 内核的对 PV 原语中 P(s) V(s) 操作的封装,

而 Mutex 其实就是 一个特殊的 信号量 Semaphore, 也就是 Semaphore 的 count 为 1 时的情况,

也就是说 Mutex 就是 PV 原语中的资源数目 s 为 1 的情况。

 

https://github.com/torvalds/linux/blob/v2.6.39/include/linux/mutex.h#L49

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_SMP)
	struct thread_info	*owner;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
	const char 		*name;
	void			*magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
	struct lockdep_map	dep_map;
#endif
};

 

https://github.com/torvalds/linux/blob/v2.6.39/include/linux/mutex.h#L105

#define __MUTEX_INITIALIZER(lockname) \
		{ .count = ATOMIC_INIT(1)  //<--------------- \
		, .wait_lock = __SPIN_LOCK_UNLOCKED(lockname.wait_lock) \
		, .wait_list = LIST_HEAD_INIT(lockname.wait_list) \
		__DEBUG_MUTEX_INITIALIZER(lockname) \
		__DEP_MAP_MUTEX_INITIALIZER(lockname) }

 

posted @ 2021-09-25 15:23  zjsxwc  阅读(148)  评论(0编辑  收藏  举报