当前位置: 代码迷 >> 综合 >> usleep(0)与sched_yield()
  详细解决方案

usleep(0)与sched_yield()

热度:13   发布时间:2024-02-02 15:36:50.0

结论:

       如果你是为了耗掉一个机器周期 ,那直接asm ("nop") ,

  如果是为了让权,建议把 所有使用 usleep(0)  换成 sched_yield() ;

 

sched_yield() 的man手册:

SYNOPSIS

        #include <sched.h>

        int sched_yield(void);

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.

(sched_yield()会让出当前线程的CPU占有权,然后把线程放到静态优先队列的尾端,然后一个新的线程会占用CPU。

【如果没有符合条件的线程,那么这个函数将会立刻返回然后继续执行当前线程的程序。】)

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.

什么时候使用:

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()能在资源竞争情况很严重时,通过给其他的线程或进程运行机会的方式来提升程序的性能)

 usleep(0):

特点:非主动让权,调用了 deactivate_task(),因此延迟高,和sched_yield()慢了一个数量级。

主要目的是:交出当前线程的执行权,让CPU去执行其他线程。也就是放弃当前线程的时间片,转而执行其他线程。

sleep(0):

待补充。

感谢:

sleep(0)、usleep(0)与sched_yield() 调度

 

  相关解决方案