[linux kernel]semaphore信号量的用法

struct semaphore {

raw_spinlock_t lock; --->锁

unsigned int count;--->信号量计数

struct list_head wait_list;--->信号量等待链表

};

struct semaphore_waiter {

struct list_head list;

struct task_struct *task;

bool up;

};

两个关键函数:

/**

* 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);

/**

* 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;

raw_spin_lock_irqsave(&sem->lock, flags);

if (likely(sem->count > 0))

sem->count--;

else///< 小于等于0

__down(sem);

raw_spin_unlock_irqrestore(&sem->lock, flags);

}

EXPORT_SYMBOL(down);

相关推荐
女神下凡21 分钟前
芯易选(133):建荣(AppoTech)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件
Decay__1 小时前
PostgreSQL 索引与 SQL 优化 —— B-tree、GiST、GIN、BRIN、执行计划与索引设计实战
运维·数据库·sql·postgresql
JWIPC2 小时前
MyClaw 3.0 自动化数据采集实战指南
linux·运维·笔记·科技·深度学习·物联网·自动化
Kainy2 小时前
生产服务器从机械盘迁移NVMe固态:旧盘不动、退路先行的六步实操全记录
运维·服务器
Flynt2 小时前
自托管重开实录:照 HN 419 分热帖让 AI 从零搭一遍,15 分钟踩了三个真坑
linux·开源·ai编程
Henry-SAP3 小时前
SAP BOM项目类别详解——L/T/R/N各类目的业务含义解析
运维
天空属于哈夫克34 小时前
企业微信二次开发:解锁更多自动化应用场景
运维·自动化·企业微信
EmbeddedChen4 小时前
Linux 怎么查看 IP 地址和网络状态?常用网络命令入门
linux·网络·ip·route·ping
Diligently_4 小时前
第 08 篇|单机部署:本地安装与 Docker 最佳实践
运维·spring boot·docker
大今野5 小时前
2026 专转本计算机|区块链典型框架:以太坊与超级账本 Fabric 考点全解(附例题)
运维·区块链·fabric·专转本