虽然可以使用信号量来表示互斥锁,但是互斥锁其实是存在的,只是前面的宏DECLARE_MUTEX因为会引起歧义,所以修改成了DEFINE_SEMAPHORE,mutex在2.6.16版本就融入到了主内核中了,使用mutex需要包含头文件<linux/mutex.h>,例如:
/* Statically declare a mutex. To dynamically create a mutex, use mutex_init() */ static DEFINE_MUTEX(mymutex); /* Acquire the mutex. This is inexpensive if there * is no one inside the critical section. In the face of * contention, mutex_lock() puts the calling thread to sleep. */ mutex_lock(&mymutex); /* Critical Section code ... */ mutex_unlock(&mymutex); /* Release the mutex */
使用宏DEFINE_MUTEX静态定义和初始化一个互斥锁,如果需要动态初始化,那么使用函数mutex_init(),原型如下:
void mutex_init(struct mutex *mutex);
mutex_lock和mutex_unlock分别是对临界区进行加锁和解锁,机制同信号量都差不多,在临界区不能被访问是引起进程的休眠而不是忙等。同信号量一样,mutex也有mutex_lock_interruptible和mutex_trylock,所有的函数原型如下:
void mutex_lock(struct mutex *lock); int mutex_lock_interruptible(struct mutex *lock); int mutex_trylock(struct mutex *lock); void mutex_unlock(struct mutex *lock);