usleep(0)与sched_yield() 调度及cpu_relax()

本文讨论了在Linux中,usleep(0),sched_yield()和cpu_relax()在性能优化中的微妙差异。cpu_relax适合短锁持有,避免频繁任务切换;sched_yield导致内核态切换,虽耗时但可能更有效;usleep触发任务调度,成本更高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结论:重量级usleep(0) > sched_yield() > cpu_relax()

1、cpu_relax()用于短时间的忙等待,比如每个用户持锁的时间很短,让出cpu的代价不如忙等待。它和死循环等待的区别是,cpu空转功耗会低。

Note that "cpu_relax" is not a "sched_yield()". You haven't gotten to the point where you want to do a system call yet, you're way before that point. It's a "CPU core yield" - "rep nop" in x86.

2、sched_yield会调用sched_yield系统调用。

所以一定会陷入内核态,触发任务切换。

3、usleep(n)会调用nanosleep系统调用

所以一定会陷入内核态,调用deactivate_task触发任务调度,然后进行任务切换。而任务调度是比较耗时的。

https://www.cnblogs.com/schips/p/11002589.html

Real World Technologies - Forums - Thread: Nuances related to Spinlock implementation and the Linux Scheduler
性能优化之sleep、sched_yield和忙等待 - 简书

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值