Buddy算法实现

来源:互联网 发布:怎么申请淘宝账号 编辑:程序博客网 时间:2024/05/21 17:05
Buddy算法是为了解决linux内存管理提出的一种高效管理算法,主要解决内存碎片问题,其基本思路如下:
首先把内存中的页框(一个页框大小4kb,对应一个页面,物理的)分为连续的1,2,4,8,16,32,64,128,256,512,1024个页框数量,这样当你需要分配6个页面时,首先查看连续8个页面中大小是否为1,如果是则直接将这8个页面分配出去,如果连续8个页面也没有就去看连续16个页面是否存在有就拆分为两个连续8个页面,其中一个分配出去,另一个则将分给那个连续的8个页面共下次分配,直到1024个页面,若没有则分配失败。合并内存就是这个过程的反过程。
具体代码如下:
#include <stdio.h>
#include <stdlib.h>

struct Info
{
    int value;
    int count;  
    int begin;
    int end;     
};

void init(struct Info info[])
{
    int i;
    for(i=0; i<11; i++)
    {
        if(i == 0)  info[i].value = 1;
        else info[i].value = info[i-1].value*2;
        info[i].count = 0;   
        info[i].begin = 0;
        info[i].end = 0;    
    }
    info[10].count = 1; 
    info[10].end = 1023;    
}

void print(struct Info info[])
{
    int i;
    for(i=0; i<11; i++)
    {
        printf("size=%4d    count=%d  ", info[i].value, info[i].count);
        if(info[i].count > 0)
        {
            printf("   %4d ~ %4d\n", info[i].begin, info[i].end);                 
        }     
        else  {  printf("\n");  }
            
    }     
}

void buddy(struct Info info[], int num)
{
    int i, j, k; 
    for(i=0; i<11; i++)
    {
        if(info[i].value >= num)
        {
            if(info[i].count == 1)
            {
                info[i].count = 0;
                printf("Allocate pages succefully!\n"); 
                return ;                
            }
            else
            {
                for(j=i; j<11; j++)
                {
                    if(info[j].count == 1)
                    {
                        info[j].count = 0;             //把该页拆分开 
                        for(k=i; k<j; k++)
                        {
                            info[k].count = 1;
                            info[k].begin = info[k].value;
                            info[k].end = info[k].begin*2 - 1;         
                        }   
                        printf("Allocate pages succefully!\n");
                        return ;             
                    }   
                    if(j == 10)  
                    {
                        printf("Allocate pages failed!\n");
                        return ; 
                    }
                }    
            }
        }         
    }    
}

int main()
{
    int i, num;
    struct Info info[11];
    printf("Init:\n");
    init(info);
    
    print(info);
    while(1)
    {
        printf("\nPlease input a  num:");
        scanf("%d", &num);
        fflush(stdin);
        if(num > 1023)  printf("The num is too big , try littler\n");
        else
        {
            buddy(info, num);
            print(info);
        }
    }
    system("pause");
    return 0;    
}


执行界面如下:
Buddy算法 - vanpire110 - vanpire110的博客
 
Buddy算法 - vanpire110 - vanpire110的博客
 
http://vanpire110.blog.163.com/blog/static/132876356201152344214335/
原创粉丝点击