zoukankan      html  css  js  c++  java
  • Linux下的sleep()和sched_yield()(转)


    阿里四面被问到了这个问题,一脸懵逼,下来也没找到什么阐述这个的文章,就自己查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

  • 相关阅读:
    jquery click()方法模拟点击事件对a标签不生效
    键盘keyCode
    java配置好jdk-bash: /usr/bin/java: No such file or directory
    iptables配置顺序-两条规则会忽略后边的
    一些非常实用的JSON 教程
    C#实现json的序列化和反序列化
    [asp.net]C#实现json的序列化和反序列化
    一些JSON 教程
    js+JQuery实现返回顶部功能
    HTML标签总结
  • 原文地址:https://www.cnblogs.com/zl1991/p/11821534.html
Copyright © 2011-2022 走看看