Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i get the CPU number of current task (In kernel)?

Tags:

linux

kernel

Is there any way to get CPU number of current task? (What I need is not the number of CPUs the task is running on, but which CPU the task is running on)

This process must be in kernel-level, therefore something like command line won't help.

I am trying to do this by calling kernel functions or using kernel data structures(like task_struct), but I am having trouble.

like image 748
Jangwoong Kim Avatar asked Dec 12 '25 19:12

Jangwoong Kim


1 Answers

A rather old question but this might be helpful for the future:

If you have CONFIG_THREAD_INFO_IN_TASK enabled (which is usually the default) then you can simply access the current CPU of the task using the cpu member of task_struct: current->cpu

As you can find in the source:

#ifdef CONFIG_THREAD_INFO_IN_TASK
    /* Current CPU: */
    unsigned int            cpu;
#endif

And also the previous CPU of the task as could be found in task_struct:

    /*
     * recent_used_cpu is initially set as the last CPU used by a task
     * that wakes affine another task. Waker/wakee relationships can
     * push tasks around a CPU where each wakeup moves to the next one.
     * Tracking a recently used CPU allows a quick search for a recently
     * used CPU that may be idle.
     */
    int             recent_used_cpu;

You may also use cpu = task_cpu(p) which return id of the CPU.

Each task is also associated with a runqueue of a CPU. and each runqueue has a cpu field. The runqueue could be simply retrieved by rq = task_rq(p) and then rq->cpu.

like image 103
Mohammad Siavashi Avatar answered Dec 15 '25 10:12

Mohammad Siavashi