Zinedin Zidane
Zinedin Zidane

Reputation: 112

How to execute an application using a specific core or cores?

I'm writing an application that needs to be executed on a specific core of a processor. For Example: If we have 4 cores and i want to execute code on 2nd core only. I need help how to do this.

Upvotes: 1

Views: 1803

Answers (2)

Adnan Qureshi
Adnan Qureshi

Reputation: 562

The programmer can prescribe his/her own affinities (hard affinities) but use the default scheduler unless a you have a good reason not to.

Here is a C/C++ function to assign a thread to a certain core from Kernel scheduler API:

#include <sched.h>

int sched_setaffinity(pid_t pid, unsigned int len, unsigned long * mask);

It sets the current affinity mask of process pid to *mask. len is the system word size (sizeof(unsigned int long))

To query affinity of a running process:

$ taskset -p 3935

Example output:

pid 3935's current affinity mask: f

Upvotes: 1

I'm writing an application that needs to be executed on a specific core of a processor.

This is extremely improbable on most platforms (since most multi-core processors are homogeneous). You really need to explain, motivate and justify such an usual requirement.

You can't do that in general. And if you could do that, how exactly you should proceed is operating system specific, and platform specific. Most multi-core processors are homogeneous (all the cores are the same), some are not.

On Linux/x86-64, the kernel scheduler sees all cores as the same, and will move a task (e.g. a thread of a multi-threaded process) from one core to another at arbitrary moments. Since scheduling is preemptive.

On some processors, moving periodically (e.g dozen of times per second) a task from one core to another is actually recommended (and done automagically by the kernel, or the firmware - e.g. SMM) to avoid overheating of that core. Read about dark silicon.

Some unusual hardware (e.g. ARM big.LITTLE) have two sets of different cores (e.g. 2 high-end ARM cores with 2 low-end ones, all sharing the same memory). If your platform is such, please state that in your question, and ask how to achieve processor affinity on your specific platform. Very likely your OS has appropriate system calls for that purpose.

Some high-end motherboards are multi-sockets. In such case, a RAM module is closer to one socket (in timing) than to another. You then care about non-uniform memory access.

So read more about processor affinity and non-uniform memory access. Most OSes have some support for both. On Linux, see pthread_setaffinity_np(3), sched_setaffinity(2), numa(7) etc...

To learn more about OSes, read Operating Systems: Three Easy pieces.

Notice that by pinning some thread to a some fixed core, you might lower the performance of your program. Since processor affinity is rarely useful.

Upvotes: 2

Related Questions