首页 > 系统服务 > 详细

Linux下的sleep()和sched_yield()(转)

时间:2019-11-08 17:50:01      阅读:93      评论:0      收藏:0      [点我收藏+]


阿里四面被问到了这个问题,一脸懵逼,下来也没找到什么阐述这个的文章,就自己查man来对比总结一下吧:

sched_yield()的man手册描述如下:

DESCRIPTION
       sched_yield()  causes  the  calling  thread to relinquish the CPU.  The  thread is moved to the end of the queue for its static priority  and  a  new thread gets to run.

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

ERRORS

       In the Linux implementation, sched_yield() always succeeds.

翻译一下,sched_yield()会让出当前线程的CPU占有权,然后把线程放到静态优先队列的尾端,然后一个新的线程会占用CPU。那这个和sleep()有啥区别呢?

sched_yield()这个函数可以使用另一个级别等于或高于当前线程的线程先运行。如果没有符合条件的线程,那么这个函数将会立刻返回然后继续执行当前线程的程序。 

而sleep则是等待一定时间后等待CPU的调度,然后去获得CPU资源(这也是usleep()为什么不准的原因)。

那么什么时候使用sched_yield()呢?man手册是这么说的

 Strategic calls to sched_yield()  can  improve  performance  by  giving other  threads  or processes  a chance to run when (heavily) contended  resources (e.g., mutexes) have been  released  by  the  caller.

翻译一下,有策略的调用sched_yield()能在资源竞争情况很严重时,通过给其他的线程或进程运行机会的方式来提升程序的性能。也就是说,调用sched_yield()能让你的当前线程让出资源,通过一定的策略调用sched_yield()满足你的业务要求可以保证各个线程或进程都有机会运行。
————————————————
版权声明:本文为CSDN博主「曾柯」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zk3326312/article/details/79624199

Linux下的sleep()和sched_yield()(转)

原文:https://www.cnblogs.com/zl1991/p/11821534.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!