关于sched_yield()主动出让CPU的占有权

有时候程序在一个死循环中执行,不断尝试获取某个资源,如果没有获得就会不断尝试。为了防止程序空跑,可以调用sched_yield函数来主动出让CPU的占有权,减少CPU的空跑。比如自旋锁的实现可以调用sched_yield来减少CPU的空跑。
man一下,查看一下手册:

NAME
       sched_yield - yield the processor

SYNOPSIS
       #include <sched.h>

       int sched_yield(void);

DESCRIPTION
       A  process can relinquish the processor voluntarily without blocking by calling sched_yield().  The process will then be moved
to the end of the queue for its static priority and a new process gets to run.

       Note: If the current process is the only process in the highest priority list at that time, this process will continue to run
after a call to sched_yield().

       POSIX systems on which sched_yield() is available define _POSIX_PRIORITY_SCHEDULING in <unistd.h>.

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

文档的大致意思是,通过调用sched_yield函数可以使当前线程以非阻塞方式主动放弃处理器时间片的使用,并根据其优先级别将其放到对应调度队列的
队尾,从而使另一个级别等于或高于当前线程的线程先运行。如果没有高于或者等于当前线程优先级别的线程,那么这个函数会立即返回继续执行当前
线程。

对于放弃CPU的主动权可以用sleep,调用sleep也会让出CPU的占有权,不过不同之处在于,sleep会等待一段时间后再等待CPU的调度。

猜你喜欢

转载自blog.csdn.net/qq_19825249/article/details/107975760
今日推荐