互斥体提供了两种机制:经典互斥体和实时互斥体
分别定义于#include<linux/mutex.h> #include<linux/trmutex.h>
经典互斥体结构体: (会导致
无限制优先级反转问题)
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 task_struct
*owner;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
const char
*name;
void
*magic;
#endif
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map
dep_map;
#endif
};
实时互斥体结构体:
struct rt_mutex {
raw_spinlock_t
wait_lock;
struct
plist_head
wait_list;
struct task_struct
*owner;
#ifdef CONFIG_DEBUG_RT_MUTEXES
int
save_state;
const char
*name, *file;
int
line;
void
*magic;
#endif
};
操作:
struct mutex my_mutex;
mutex_init(&my_mutex);
void mutex_lock(struct mutex* lock);
//获取互斥体,不可被信号中断
void mutex_lock_interruptible(struct mutex* lock);
//获取互斥体,可被信号打断
int mutex_trylock(struct mutex* lock);
//尝试获取互斥体
void mutex_unlock(struct mutex* lock);
//释放互斥体
int mutex_is_locked(struct mutex* lock):
该函数检查互斥锁lock是否处于锁定状态。返回1,表示已锁定;返回0,表示未锁定;
int mutex_lock_interruptible(struct mutex* lock); //该函数可被信号打断
int mutex_lock_killable(struct mutex* lock); //该函数可被kill信号打断
用例:
struct mutex my_mutex;
mutex_init(&my_mutex);
mutex_lock(&my_mutex);
...临界区...
mutex_unlock(&my_mutex);