Process and cpu

Now there are 2 cpu cores core, 4-core, 8-core or more

Then the application can get the number of core cpu it? The answer is yes, you can get through the code below

#include<stdio.h>

#include<sys/syscall.h>

#include<unistd.h>

 

#define __USE_GNU

int main ()

{

  unsigned num = sysconf(__SC_NPROCESSORS_CONF);

  printf("cpu cores:%d\n",num);

}

 

Then, after obtaining the cpu cores what use is it?

 

Look as a function

int cpu_bind(int num)

{

  pid_t selfid = syscall(__NR_gettid);

  cpu_set_t mask;

  CPU_ZERO(&mask);

  CPU_SET(selfid%num,&mask);

 

  sched_setaffinity(0,sizeof(mask),&mask);

}

 

 

As the name suggests, cpu_bind should be on the implementation of cpu binding operation, then what does bind

 

Effect syscall (__ NR_gettid) is substantially equivalent to getpid, which means that the system acquisition schedule entity id

 

 

cpu_set_t how there is a data do, we can understand that correspond to the internal storage of a number of core cpu an array

 

CPU_ZERO role is to empty the array, the array is about all elements endowed 0

 

CPU_SET several means is a location of the array 1

 

It is not particularly like FD_ZERO, FD_SET ah, yes, just like him

 

The role of the following sched_setaffinity see out of it, its role is to present the current process or thread is bound to the array is set to 1 on the cpu core, since then the thread can only dispatch to the core of the

 

This time to understand it? Then someone will ask, what good do, why do it, which has to do with the operating system scheduler

When the operating system scheduler is ready thread on the cpu core queuing, when the thread is blocked or sleep on the withdrawal from the cpu core, and pressed state register into memory. It is then queued to a ready thread begins execution removed from memory into the register

A thread does not always routed to the fixed core cpu, so there will be multiple threads of a process line up on the same core cpu

This may result in decreased efficiency of the program

This article describes the use of approach allows to enhance the efficiency of the implementation process

 

Guess you like

Origin www.cnblogs.com/zhangrd/p/11590364.html