当前位置: 首页 > article >正文

linux semaphore信号量操作

信号量(semaphore)是操作系统中最常见的同步原语之一。

spinlock是实现忙等待锁,而信号量则允许进程进入睡眠状态。

下面将分析信号量的获取是释放操作。

1、数据结构

数据结构定义和初始化如下:

include/linux/semaphore.h

/* Please don't access any members of this structure directly */

struct semaphore {

raw_spinlock_t lock;

unsigned int count;

struct list_head wait_list;

};

/* Functions for the contended case */

struct semaphore_waiter {

struct list_head list;

struct task_struct *task;

bool up;

};

struct semaphore_waiter数据结构用于描述获取信号量失败的进程,每个进程会有一个struct semaphore_waiter数据结构,并且把当前进程放到信号量sem的成员变量wait_lsit链表中。

信号量初始化:

/*定义和申明的信号量count值为1*/

#define DEFINE_SEMAPHORE(name) \

struct semaphore name = __SEMAPHORE_INITIALIZER(name, 1)

#define __SEMAPHORE_INITIALIZER(name, n) \

{ \

.lock = __RAW_SPIN_LOCK_UNLOCKED((name).lock), \

.count = n, \

.wait_list = LIST_HEAD_INIT((name).wait_list), \

}


static inline void sema_init(struct semaphore *sem, int val)

{

static struct lock_class_key __key;

*sem = (struct semaphore) __SEMAPHORE_INITIALIZER(*sem, val);

/*未定义 CONFIG_LOCKDEP,lockdep_init_map为空操作*/

lockdep_init_map(&sem->lock.dep_map, "semaphore->lock", &__key, 0);

}

2、信号量的实现

内核中涉及信号量操作接口如下:

void down(struct semaphore *sem);

int __must_check down_interruptible(struct semaphore *sem);

int __must_check down_killable(struct semaphore *sem);

int __must_check down_trylock(struct semaphore *sem);

int __must_check down_timeout(struct semaphore *sem, long jiffies);

void up(struct semaphore *sem);

下面分析其具体实现:

/**
 * down - acquire the semaphore
 * @sem: the semaphore to be acquired
 *
 * Acquires the semaphore.  If no more tasks are allowed to acquire the
 * semaphore, calling this function will put the task to sleep until the
 * semaphore is released.
 *
 * Use of this function is deprecated(强烈反对), please use down_interruptible() or  down_killable() instead.
 */
void down(struct semaphore *sem)
{
	unsigned long flags;

	/*关闭本地CPU中断+spin_lock*/
	raw_spin_lock_irqsave(&sem->lock, flags);

	if (likely(sem->count > 0)) /*存在可用信号量,直接取走(count--) */
		sem->count--;
	else
		__down(sem); /*无可用信号量,当前进程休眠*/

	/*恢复本地CPU中断+spin_unlock*/
	raw_spin_unlock_irqrestore(&sem->lock, flags);
}
/**
 * down_interruptible - acquire the semaphore unless interrupted
 * @sem: the semaphore to be acquired
 *
 * Attempts to acquire the semaphore.  If no more tasks are allowed to
 * acquire the semaphore, calling this function will put the task to sleep.
 * If the sleep is interrupted by a signal, this function will return -EINTR.
 * If the semaphore is successfully acquired, this function returns 0.
 */
int down_interruptible(struct semaphore *sem)
{
	unsigned long flags;
	int result = 0;

	/*关闭本地CPU中断*/
	raw_spin_lock_irqsave(&sem->lock, flags);

	if (likely(sem->count > 0))
		sem->count--;
	else
		result = __down_interruptible(sem);

	/*恢复本地CPU中断*/
	raw_spin_unlock_irqrestore(&sem->lock, flags);

	return result;
}
/**
 * down_killable - acquire the semaphore unless killed
 * @sem: the semaphore to be acquired
 *
 * Attempts to acquire the semaphore.  If no more tasks are allowed to
 * acquire the semaphore, calling this function will put the task to sleep.
 * If the sleep is interrupted by a fatal signal, this function will return -EINTR. 
 *  If the semaphore is successfully acquired, this function returns
 * 0.
 */
int down_killable(struct semaphore *sem)
{
	unsigned long flags;
	int result = 0;

	/*关闭本地CPU中断*/
	raw_spin_lock_irqsave(&sem->lock, flags);

	if (likely(sem->count > 0))
		sem->count--;
	else
		result = __down_killable(sem);

	/*恢复本地CPU中断*/
	raw_spin_unlock_irqrestore(&sem->lock, flags);

	return result;
}
/**
 * down_trylock - try to acquire the semaphore, without waiting
 * @sem: the semaphore to be acquired
 *
 * Try to acquire the semaphore atomically.  Returns 0 if the semaphore has
 * been acquired successfully or 1 if it it cannot be acquired.
 *
 * NOTE: This return value is inverted from both spin_trylock and
 * mutex_trylock!  Be careful about this when converting code.
 *
 * Unlike mutex_trylock, this function can be used from interrupt context,
 * and the semaphore can be released by any task or interrupt.
 */
int down_trylock(struct semaphore *sem)
{
	unsigned long flags;
	int count;

	raw_spin_lock_irqsave(&sem->lock, flags);

	count = sem->count - 1;
	if (likely(count >= 0))
		sem->count = count;

	raw_spin_unlock_irqrestore(&sem->lock, flags);

	return (count < 0);
}
/**
 * down_timeout - acquire the semaphore within a specified time
 * @sem: the semaphore to be acquired
 * @timeout: how long to wait before failing
 *
 * Attempts to acquire the semaphore.  If no more tasks are allowed to
 * acquire the semaphore, calling this function will put the task to sleep.
 * If the semaphore is not released within the specified number of jiffies,
 * this function returns -ETIME.  It returns 0 if the semaphore was acquired.
 */
int down_timeout(struct semaphore *sem, long timeout)
{
	unsigned long flags;
	int result = 0;

	raw_spin_lock_irqsave(&sem->lock, flags);

	if (likely(sem->count > 0))
		sem->count--;
	else
		result = __down_timeout(sem, timeout);

	raw_spin_unlock_irqrestore(&sem->lock, flags);

	return result;
}
/**
 * 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;

	/*关闭本地CPU中断*/
	raw_spin_lock_irqsave(&sem->lock, flags);

	if (likely(list_empty(&sem->wait_list))) /*wait_list上无等待任务则count++,表示信号量可用数量*/
		sem->count++;
	else
		__up(sem); /*wait_list上存在等待任务,那么直接唤醒等待任务*/

	/*恢复本地CPU中断*/
	raw_spin_unlock_irqrestore(&sem->lock, flags);
}
static noinline void __sched __down(struct semaphore *sem)
{
	/*TASK_UNINTERRUPTIBLE:不可中断休眠状态*/
	__down_common(sem, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}

static noinline int __sched __down_interruptible(struct semaphore *sem)
{
	/*TASK_INTERRUPTIBLE:可中断休眠状态*/
	return __down_common(sem, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
}

static noinline int __sched __down_killable(struct semaphore *sem)
{
	return __down_common(sem, TASK_KILLABLE, MAX_SCHEDULE_TIMEOUT);
}

/*设置超时时间*/
static noinline int __sched __down_timeout(struct semaphore *sem, long timeout)
{
	/*TASK_UNINTERRUPTIBLE:不可中断休眠状态*/
	return __down_common(sem, TASK_UNINTERRUPTIBLE, timeout);
}
/*
 * Because this function is inlined, the 'state' parameter will be
 * constant, and thus optimised away by the compiler.  Likewise the
 * 'timeout' parameter for the cases without timeouts.
 */
static inline int __sched __down_common(struct semaphore *sem, long state,long timeout)
{
	struct task_struct *task = current; /*当前任务*/
	struct semaphore_waiter waiter;

	/*将waiter挂接到sem->wait_list上*/
	list_add_tail(&waiter.list, &sem->wait_list);
	waiter.task = task;
	waiter.up = false;

	for (;;) {
		if (signal_pending_state(state, task)) /*存在信号pending且任务状态为可中断休眠*/
			goto interrupted;
		if (unlikely(timeout <= 0)) /*超时*/
			goto timed_out;

		/*设置当前任务状态为state*/
		__set_task_state(task, state);
		/*	
		释放自旋锁+开启本地CPU中断,因为后面会调用schedule_timeout进行进程切换,因为自旋锁临界区不能进行休眠,当前进程被调度出去就处于休眠状态,所以释放自旋锁。
		注意在down_XXX中已经调用raw_spin_lock_irqsave关闭过本地CPU中断,这里将本地CPU中断打开.
		*/
		raw_spin_unlock_irq(&sem->lock);
		/*进行调度,当前任务被切换出去其他任务执行,返回剩余超时时间*/
		timeout = schedule_timeout(timeout);
		/*该任务再次被调度得到执行,关闭本地CPU中断*/
		raw_spin_lock_irq(&sem->lock);
		/*检查是否有可用信号量,waiter.up为true表示当前任务可以获取信号量,退出循环*/
		if (waiter.up) 
			return 0;
	}

 timed_out:
	list_del(&waiter.list);
	return -ETIME;

 interrupted:
	list_del(&waiter.list);
	return -EINTR;
}
/*释放信号量*/
static noinline void __sched __up(struct semaphore *sem)
{
	struct semaphore_waiter *waiter = list_first_entry(&sem->wait_list,
						struct semaphore_waiter, list);

	/*up 调用 raw_spin_lock_irqsave已经关闭本地CPU中断*/

	/*将wait_list的first entry删除*/
	list_del(&waiter->list);
	/*设置up成员为true*/
	waiter->up = true;
	/*唤醒因等待信号量而休眠的进程,该进程从__down_common中返回进而访问临界区*/
	wake_up_process(waiter->task);
}


http://www.kler.cn/news/324771.html

相关文章:

  • 基于nodejs+vue的农产品销售管理系统
  • 如何制作小程序商城
  • NLP任务的详细原理与步骤的详细讲解
  • 算法 求最大葫芦数
  • 如何选择合适的跨境网络专线?
  • 加速 Python for 循环
  • Unity开发绘画板——02.创建项目
  • TTPoE的设计,quic协议,KCP传输协议,快速可靠的UDP
  • 另外知识与网络总结
  • AndroidManifest.xml 文件中的 package 属性不再是强制要求定义
  • 使用6条命令完成Windows和H3C VSR的IPsec对接
  • 我想自己做一个漫画网站,我需要多大的服务器
  • cocos资源分包
  • CSS 的pointer-events属性,控制元素如何响应用户指针事件
  • 怎么给邮件加密?对邮件加密的五个绝佳方法,亲测有效!保教包会哦!
  • JIT- 栈上替换(On-Stack Replacement, OSR)
  • c++入门 类和对象(中)
  • ELK-05-skywalking监控SpringCloud服务日志
  • Java 图片合成
  • 【CKA】二、节点管理-设置节点不可用
  • UDP与TCP那个传输更快
  • 【高阶数据结构】平衡二叉树(AVL)的插入(4种旋转方法+精美图解+完整代码)
  • 深度解析:Debian 与 Ubuntu 常用命令的区别与联系
  • Electron 安装以及搭建一个工程
  • GGHead:基于3D高斯的快速可泛化3D数字人生成技术
  • TCN预测 | MATLAB实现TCN时间卷积神经网络多输入单输出回归预测
  • WPF入门教学十三 MVVM模式简介
  • 极狐GitLab 17.4 重点功能解读【二】
  • Git 工作区、暂存区和版本库
  • 从事人工智能学习Python还是学习C++?