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.
sched_yield()会导致当前线程让出CPU占有权,线程被放到静态优先队列的尾端,然后一个新的线程会被调度继续执行。
RETURN VALUE
On success, sched_yield() returns 0. On error, -1 is returned, and errno is set appropriately.
成功返回0,出错返回-1。
ERRORS
In the Linux implementation, sched_yield() always succeeds.
当前linux的实现,sched_yield()总是成功。
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()满足你的业务要求可以保证各个线程或进程都有机会运行。