阿里四面被问到了这个问题,一脸懵逼,下来也没找到什么阐述这个的文章,就自己查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()满足你的业务要求可以保证各个线程或进程都有机会运行。

GitHub 加速计划 / li / linux-dash
10
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:1 个月前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐