Article Title: cpu affinity settings. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
# Include
# Include
# Include
# Include
Int main (int argc, char * argv [])
{
Int num = sysconf (_ SC _NPROCESSORS_CONF );
Int created_thread = 0;
Int myid;
Int I;
Int j = 0;
Cpu_set_t mask;
Cpu_set_t get;
If (argc! = 2)
{
Printf ("usage:./cpu num \ n ");
Exit (1 );
}
Myid = atoi (argv [1]);
Printf ("system has % I processor (s). \ n", num );
CPU_ZERO (& mask );
CPU_SET (myid, & mask );
If (sched_setaffinity (0, sizeof (mask), & mask) =-1)
{
Printf ("warning: cocould not set CPU affinity, continuing... \ n ");
}
While (1)
{
CPU_ZERO (& get );
If (sched_getaffinity (0, sizeof (get), & get) =-1)
{
Printf ("warning: cound not get cpu affinity, continuing... \ n ");
}
For (I = 0; I <num; I ++)
{
If (CPU_ISSET (I, & get ))
{
Printf ("this process % d is running processor: % d \ n", getpid (), I );
}
}
}
Return 0;
}
After setting the cpu affinity, other started threads are bound to the corresponding CPU.
CPU Affinity (CPU Affinity)
CPU affinity means that one or more processes can be bound to one or more processors in Linux.
The CPU affinity mask of a process determines which or which CPUs the process will run on. In a multi-processor system, setting the CPU affinity mask may provide better performance.
The affinity mask of a CPU uses a cpu_set_t struct to represent a CPU set. The following macros operate on this set respectively:
CPU_ZERO () clears a set
CPU_SET () and CPU_CLR () respectively add a given CPU number to a set or remove it from a set.
CPU_ISSET () check whether a CPU number is in this collection.
In fact, the usage of these functions is similar to that of the select () function.
The following two functions are the most important ones:
Sched_setaffinity (pid_t pid, unsigned int cpusetsize, cpu_set_t * mask)
This function sets the process as pid and runs on the CPU set by the mask. if the pid value is 0, it indicates that the current process is specified, so that the current process runs on the CPU set by the mask. the second parameter cpusetsize is
The length of the number specified by the mask. usually set to sizeof (cpu_set_t ). if the CPU specified by the current pid is not running on any CPU specified by the mask at this time, the specified process will be migrated from other CPUs to the specified
Run on one CPU.
Sched_getaffinity (pid_t pid, unsigned int cpusetsize, cpu_set_t * mask)
This function obtains the CPU mask of the Process indicated by the pid and returns the mask to the structure pointed to by the mask. obtain the CPU on which the specified pid can run. similarly, if the pid value is 0. it also indicates the current process.
Original address http://www.chinaunix.net/jh/4/904906.html