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

相关推荐
薛定猫AI1 小时前
Codex 与 Claude Code 全平台安装配置指南(Windows / macOS / Linux)
linux·windows·macos
仙柒4154 小时前
Docker原理
运维·docker·容器
茉莉玫瑰花茶8 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
米高梅狮子8 小时前
第2章 docker容器
运维·docker·云原生·容器·架构·kubernetes·自动化
kidwjb9 小时前
信号量在进程中的使用
linux·进程间通信
闵孚龙9 小时前
Claude Code Ultraplan 远程多代理规划全解析:AI Agent、CCR远程容器、异步规划、状态机、计划传送与企业级自动化治理
运维·人工智能·自动化
南京码讯光电技术有限公司10 小时前
工业无线AP选型指南:从WiFi 5到WiFi 6+5G CPE,如何构建全覆盖、零漫游、高可靠的智能工厂网络?
服务器·网络·5g
sulikey10 小时前
个人Linux操作系统学习笔记2 - gcc与库的理解
linux·笔记·学习·操作系统·gcc·
二宝哥11 小时前
Linux虚拟机网络配置
linux·运维·服务器
卧室小白11 小时前
docker网络与服务编排与集群
运维·docker·容器