关于linux内核中的信号量up()和mutex_unlock()

时间:2018-02-09 09:49:31

标签: linux-kernel mutex semaphore

我想知道为什么我们可以在中断上下文中使用信号量up(),而mutex的相同变量,即mutex_unlock()不能在中断上下文中使用。 以下是内核的片段

/**
* mutex_unlock - release the mutex
* @lock: the mutex to be released
*
* Unlock a mutex that has been locked by this task previously.
*
* This function must not be used in interrupt context. Unlocking
* of a not locked mutex is not allowed.
*
* This function is similar to (but not equivalent to) up().
*/
void __sched mutex_unlock(struct mutex *lock)
{
  #ifndef CONFIG_DEBUG_LOCK_ALLOC
  if (__mutex_unlock_fast(lock))
    return;
#endif
__mutex_unlock_slowpath(lock, _RET_IP_);
}EXPORT_SYMBOL(mutex_unlock);


 /**
 * up - release the semaphore
* @sem: the semaphore to release
*
* Release the semaphore.  Unlike mutexes, up() may be called from any
* context and even by tasks which have never called down().
*/
void up(struct semaphore *sem)
{
  unsigned long flags;

  raw_spin_lock_irqsave(&sem->lock, flags);
  if (likely(list_empty(&sem->wait_list)))
    sem->count++;
  else
     __up(sem);
  raw_spin_unlock_irqrestore(&sem->lock, flags);
}
EXPORT_SYMBOL(up);

1 个答案:

答案 0 :(得分:2)

mutex_unlock需要mutex-internal spinlock in a non-irq-safe fashion - 例如如果设置了raw_spin_lockCONFIG_PREEMPT_RT可能会休眠 - 所以如果时机正确,则IRQ上下文中的mutex_unlock将会死锁。