牵着老婆满街逛

严以律己,宽以待人. 三思而后行.
GMail/GTalk: yanglinbo#google.com;
MSN/Email: tx7do#yahoo.com.cn;
QQ: 3 0 3 3 9 6 9 2 0 .

Linux下多CPU中进程与CPU绑定的例子

转载自:http://www.chinaunix.net/jh/4/904906.html

现在多CPU的趋势越来越大了. 有时候为了更好地操作机器, 需要将某个进程绑定到具体的CPU上去. 下面给出了一个进程绑定到具体的CPU上去的一个例子.  

#include<stdlib.h> 
#include
<stdio.h> 
#include
<sys/types.h> 
#include
<sys/sysinfo.h> 
#include
<unistd.h> 

#define __USE_GNU 
#include
<sched.h> 
#include
<ctype.h> 
#include
<string.h> 

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(0sizeof(mask), &mask) == -1
        

                printf(
"warning: could not set CPU affinity, continuing\n"); 
        }
 
        
while (1
        


                CPU_ZERO(
&get); 
                
if (sched_getaffinity(0sizeof(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
}
 


下面是在两个终端分别执行了./cpu 0  ./cpu 2 后得到的结果. 效果比较明显.  
Cpu0  :  5.3%us,  5.3%sy,  0.0%ni, 87.4%id,  0.0%wa,  0.0%hi,  2.0%si,  0.0%st 
Cpu1  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu2  :  5.0%us, 12.2%sy,  0.0%ni, 82.8%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu3  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu4  :  0.0%us,  0.0%sy,  0.0%ni, 99.7%id,  0.3%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu5  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu6  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 
Cpu7  :  0.0%us,  0.0%sy,  0.0%ni,100.0%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st 

posted on 2010-10-31 15:54 杨粼波 阅读(946) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理