关于sched_yield()主动出让CPU的占有权

有时候程序在一个死循环中执行,不断尝试获取某个资源,如果没有获得就会不断尝试。为了防止程序空跑,可以调用sched_yield函数来主动出让CPU的占有权,减少CPU的空跑。比如自旋锁的实现可以调用sched_yield来减少CPU的空跑。
man一下,查看一下手册:

NAME
       sched_yield - yield the processor

SYNOPSIS
       #include <sched.h>

       int sched_yield(void);

DESCRIPTION
       A  process can relinquish the processor voluntarily without blocking by calling sched_yield().  The process will then be moved
to the end of the queue for its static priority and a new process gets to run.

       Note: If the current process is the only process in the highest priority list at that time, this process will continue to run
after a call to sched_yield().

       POSIX systems on which sched_yield() is available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

RETURN VALUE
       On success, sched_yield() returns 0.  On error, -1 is returned, and errno is set appropriately.

文档的大致意思是,通过调用sched_yield函数可以使当前线程以非阻塞方式主动放弃处理器时间片的使用,并根据其优先级别将其放到对应调度队列的
队尾,从而使另一个级别等于或高于当前线程的线程先运行。如果没有高于或者等于当前线程优先级别的线程,那么这个函数会立即返回继续执行当前
线程。

对于放弃CPU的主动权可以用sleep,调用sleep也会让出CPU的占有权,不过不同之处在于,sleep会等待一段时间后再等待CPU的调度。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值