Linux内核 yield()

函数:yield( )

文件包含:

        #include <linux/sched.h>

函数定义:

在内核源码中的位置:linux-3.19.3/kernel/sched.c

函数定义格式:void yield(void)

函数功能描述:

该函数实现当前进程所占用内核空间的短暂的让步,即当前进程短暂的释放其占用的CPU资源,给其他进程执行的机会,短暂的让步之后,当前进程会继续执行。函数yield( )在执行时不会改变当前进程的状态,并调用函数set_current_state( )设置当前进程为TASK_RUNNING状态。

输入参数说明:

此函数不需要任何类型的参数。

返回参数说明:

此函数不返回任何类型的值。

实例解析:

编写测试文件:yield.c

头文件引用:

#include <linux/module.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/kthread.h>
MODULE_LICENSE("GPL");

子进程函数定义:

int my_function(void * argc)
{
    printk("in the kernel thread function! \n");
    printk("the current pid is:%d\n", current->pid); //显示当前进程的PID
    printk("out the kernel thread function\n");
    return 0;
}

模块加载函数定义:

static int __init yield_init(void)
{
    struct task_struct * result;
    char namefrm[]="yield.c";
    printk("into yield_init.\n");
    result=kthread_create_on_node(my_function, NULL, -1, namefrm); //创建新进程
    wake_up_process(result);
    yield( );      //阻塞父进程,使子进程执行
    printk("the pid of new thread is:%d\n", result->pid);
                   //显示函数kthread_create_on_node( )的返回结果pid
    printk("the current pid is:%d\n", current->pid); //显示当前进程的PID
    printk("out yield_init.\n");
    return 0;
}

模块退出函数定义:

static void __exit yield_exit(void)
{
    printk("<0>Goodbye yield\n");
}

模块加载、退出函数调用:

module_init(yield_init);
module_exit(yield_exit);

实例运行结果及分析:

首先编译模块,执行命令insmod yield.ko,然后输入命令dmesg -c,会出现如图所示的结果。

Linux内核 yield()

结果分析:

由图可以看出在父进程执行的过程中,子进程被调度执行了,子进程执行之后,父进程被重新调度执行,如果没有语句“yield( ); ”,父进程一般会首先执行完毕,而子进程不会在父进程结束之前被调度执行。

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!