通常情况下,我们必须做这样从一个函数指针调用一个函数:从函数指针调用函数而不分配?
int foo()
{
}
int main()
{
int (*pFoo)() = foo; // pFoo points to function foo()
foo();
return 0;
}
在Linux内核代码,sched_class有许多函数指针:
struct sched_class {
const struct sched_class *next;
void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags);
void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags);
void (*yield_task) (struct rq *rq);
bool (*yield_to_task) (struct rq *rq, struct task_struct *p, bool preempt);
.....
}
在pick_next_task功能,它定义一个名为class
的本地实例sched_class
,并直接调用其中的功能,而不用分配给具有相同签名的外部函数(从for_each_class
开始):
static inline struct task_struct *
pick_next_task(struct rq *rq)
{
const struct sched_class *class;
struct task_struct *p;
/*
* Optimization: we know that if all tasks are in
* the fair class we can call that function directly:
*/
if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
p = fair_sched_class.pick_next_task(rq);
if (likely(p))
return p;
}
for_each_class(class) {
p = class->pick_next_task(rq);
if (p)
return p;
}
BUG(); /* the idle class will always have a runnable task */
}
这是因为在sched_class
每个函数指针具有相同的名称与实际实现的功能,所以每次通话通过的sched_class
函数指针做,它会自动找到在内核地址空间匹配的符号?