• lwip之mem


    mem概述、mem的作用

    在LwIP中,内存管理部分由mem.h、mem.c中实现,支持多种分配策略,比较灵活。支持运行时库自带的内存分配(MEM_LIBC_MALLOC),内存池分配(MEM_USE_POOLS),动态内存堆分配,这些分配策略可以通过宏定义来更改。在嵌入式系统里面,C运行时库自带的内存分配一般情况下很少用,更多的是后面二者。

    mem的结构(分析使用pool的情况)

    struct mem { 
    /** index (-> ram[next]) of the next struct */ 
    mem_size_t next; 
    /** index (-> ram[next]) of the next struct */ 
    mem_size_t prev; 
    /** 1: this area is used; 0: this area is unused */ 
    u8_t used; 
    };
    
    
    

    图示

    接口函数

    /** 
    * Zero the heap and initialize start, end and lowest-free 
    */ 
    void mem_init(void);
    
    /** 
    * Put a struct mem back on the heap 
    * 
    * @param rmem is the data portion of a struct mem as returned by a previous 
    * call to mem_malloc() 
    */ 
    void mem_free(void *rmem)
    
    
    

    mem源码分析

    全局变量

    /** the heap. we need one struct mem at the end and some room for alignment */ 
    static u8_t ram_heap[MEM_SIZE_ALIGNED + (2*SIZEOF_STRUCT_MEM) + MEM_ALIGNMENT]; 
    /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */ 
    static u8_t *ram; 
    /** the last entry, always unused! */ 
    static struct mem *ram_end; 
    /** pointer to the lowest free block, this is used for faster search */ 
    static struct mem *lfree;
    

    lwip初始化时在内存中开辟ram供使用!可以使用的内存大小为MEM_SIZE,在每一块已分配的内存块的顶端都有一个这样的结构体,所有内存块被链接为双向链表,全局变量struct mem*lfree指向最后一个未使用的mem.

    void mem_init(void) 
    { 
    struct mem *mem;
    
    LWIP_ASSERT("Sanity check alignment", (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT-1)) == 0);
    
    /* align the heap */ 
    ram = LWIP_MEM_ALIGN(ram_heap); 
    /* initialize the start of the heap */ 
    mem = (struct mem *)ram; //ram为全局变量
    //next和prev并不是指针,他们只是代表下一个(前一个)可使用的内存块大小
    mem->next = MEM_SIZE_ALIGNED; 
    mem->prev = 0; 
    mem->used = 0; 
    /* initialize the end of the heap */ 
    ram_end = (struct mem *)&ram[MEM_SIZE_ALIGNED]; 
    ram_end->used = 1;//不能再分了 
    ram_end->next = MEM_SIZE_ALIGNED; 
    ram_end->prev = MEM_SIZE_ALIGNED;
    
    mem_sem = sys_sem_new(1);//申请信号量,同步用
    /* initialize the lowest-free pointer to the start of the heap */ 
    lfree = (struct mem *)ram;
    
    MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED); 
    }
    
    
    

    总结

  • 相关阅读:
    JSPatch 可以让你用 JavaScript 书写原生 iOS APP
    iOS如何解析crash文件中的地址
    这几个Xocode插件用过一段时间还比较稳定好用,Xcode6兼容,推荐给大家:
    你的下拉刷新是否“抖”了一下
    iOS上Delegate的悬垂指针问题
    UITableView性能优化
    block详解
    runloop timer
    图片知识总结
    视像会议软件推荐备忘
  • 原文地址:https://www.cnblogs.com/westfly/p/1899541.html
Copyright © 2020-2023  润新知