首页 > 系统相关 >linux semaphore信号量操作

linux semaphore信号量操作

时间:2024-09-25 16:20:30浏览次数:11  
标签:__ down struct lock semaphore 信号量 linux sem

信号量(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);
}

标签:__,down,struct,lock,semaphore,信号量,linux,sem
From: https://blog.csdn.net/qq_30896803/article/details/142526805

相关文章

  • Linux常用命令(Mysql)
    --删除表内数据(Mysql)usedc;#切换到待删除表所在的数据库truncatetable[表名]#删除表--数据库导入SQL文件数据(Mysql)sourcea.sql;--SQL增删改查insertintostudent(id,name,sex,birth)values('01','赵雷','男','1990');deletefromstudentwhereid=......
  • Linux安装MQTT 服务器(图文教程)
    MQTT(MessageQueuingTelemetryTransport)是一种轻量级的消息传输协议,专为低带宽和不稳定的网络环境设计,非常适合物联网(IoT)应用。官网地址:https://www.emqx.com/一、版本选择根据自己的操作系统进行下载即可,推荐使用rpm安装方式。下载地址:https://www.emqx.com/zh/downloads-and-i......
  • Linux中MySQL配置主主复制操作
    一、GTIDGTID(GlobalTransactionIdentifier)是MySQL的一种用于标识分布式环境中事务的全局唯一标识符。它在MySQL的主从复制场景中尤为重要,尤其是在使用MariaDB或MySQL5.6及更高版本的环境中。GTID由两部分组成:服务器ID(标识执行该事务的服务器)和事务序号(表示在该服务器上执......
  • 女生学Linux云计算怎么样?
    现如今,生活压力较大,就业找工作也比较难,而为了能够获得满意的工作、稳定的发展,很多小伙伴都想要找一个薪酬高的行业,于是不少人将目光瞄准IT行业。而作为当下热门的技术,Linux云计算成为香饽饽,那么0基础女生转行学Linux云计算难吗?以下是详细的内容介绍。首先,我可以肯定的告诉......
  • linux 切换阿里云镜像源
    目录linux切换阿里云镜像源备份原有文件:创建阿里云CentOS仓库文件:清理缓存并更新软件包列表:测试是否成功:linux切换阿里云镜像源centos7安装好后,发现外网可以ping通,但是yum一直报错,看报错内容为镜像源问题于是切换镜像源备份原有文件:在进行任何更改之前,请确保备份原有的仓......
  • 【越学学糊涂的Linux系统】Linux指令篇(2)
    一、echo指令:✔️✔️在终端中显示文本内容或向文件中写入文本Ⅰ.基本用法:0x00打印字符串:打印字符串/显示文本内容;可以用双引号作为文本内容⬇️⬇️更推荐用单引号这里我将字符串打印出来了。和printf的功能一样;......
  • linux集群 keepalived+nginx实现高可用集群
    用keepalived配置高可用搭建高可用集群高可用集群,即“HA集群”,也常称作“双机热备”,用于关键业务。常见实现高可用的开源软件有heartbeat和keepalived,其中keepalived还有负载均衡的功能。这两个软件类似,核心原理都是通过心跳线连接两台服务器,正常情况下由一台服务器提供服务,......
  • centos(linux):用命令设置用户的shell以及/bin/false和/sbin/nologin的区别
    一,/bin/false和/sbin/nologin作为shell时的区别1,/bin/false/bin/false是一个什么都不做,立即返回非零退出状态的命令。它通常用于禁止用户登录用户不会收到任何错误或提示信息,登录尝试简单地被拒绝,没有任何解释2,/sbin/nologin/sbin/nologin是一个专门设计来阻止用户登录的程......
  • Linux 启动系统的过程中使用rd.break 在断点前进入shell
    参考:https://man7.org/linux/man-pages/man7/dracut.cmdline.7.html使用rd.break={cmdline|pre-udev|pre-trigger|initqueue|pre-mount|mount|pre-pivot|cleanup}droptoashellbeforethedefinedbreakpointstarts介绍rd.break参数允许您在内核启动过程中......
  • 常用Linux、Kubectl命令
    --查看容器报错kubectldescribepod[pod名称]kubectllogs[pod名称]--宿主机Mysql数据备份(无环境变量配置)Mysql存放文件下,找到bin/目录,并执行./mysqldump-h127.0.0.1-uroot-p--all-databases>/dc/a.sql#/dc/a.sql可更改,其中/dc/为目录,a.sql为Mysql备份的文件......