用户程序内存分配缓存简易实现

c 复制代码
/**
 * memca.c
 * 应用程序内存缓存简易实现
 * 
 * 用于尝试解决在内存分配偶现耗时问题
 * 
 * memca 不要求额外内存用于此处管理
 * 正因为如此,所缓存内存单元最小为
 * 指针大小(sizeof(void *))
 */
#include "memca.h"
#include <stdlib.h>

#define MEMCA_MAX(a, b) ((a) > (b) ? (a) : (b))
#define MEMCA_MUTEX(m)  ({\
    (m) = (pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER;\
})

void memca_init (struct memca_s *ma)
{
    uint16_t size = MEMCA_MAX(ma->size, sizeof(void *));
    uint32_t max  = ma->max;
    void *last = NULL;
    
    ma->head = ma->num = 0;
    MEMCA_MUTEX(ma->lock);
    ma->size = size;

    while (max--) {
        void *v = malloc(size);
        if (!v)
            return ;
        if (!last) {
            ma->head = last = v;
        } else {
            *(void **) last = v;
            last = v;
        }
        *(void **)v = NULL;
        ma->num += 1;
    }
    return ;
}

void memca_close(struct memca_s *ma)
{
    void *v;

    while ((v=ma->head)) {
        ma->head = *(void **)v;
        ma->num -= 1;
        free(v);
    }
    return ;
}

void * memca_alloc(struct memca_s *ma)
{
    void *v;

    pthread_mutex_lock(&ma->lock);
    if ((v=ma->head)) {
        ma->head = *(void **)v;
        ma->num -= 1;
    }
    pthread_mutex_unlock(&ma->lock);
    return v ?: malloc(ma->size);
}

void memca_free(struct memca_s *ma, void *v)
{
    pthread_mutex_lock(&ma->lock);
    if (ma->num < ma->max) {
        *(void **)v = ma->head;
        ma->head = v;
        ma->num += 1;
        v = NULL;
    }
    pthread_mutex_unlock(&ma->lock);
    free(v);
    return ;
}
c 复制代码
#ifndef MEMCA_H
#define MEMCA_H

#include <inttypes.h>
#include <pthread.h>

struct memca_s {
    const char *name;
    uint16_t size;

    pthread_mutex_t lock;
    uint32_t max;
    uint32_t num;
    void *head;
};

void memca_init (struct memca_s *ma);
void memca_close(struct memca_s *ma);

void * memca_alloc(struct memca_s *ma);
void   memca_free (struct memca_s *ma, void *v);
#endif

简单略有内涵。

相关推荐
難釋懷7 小时前
Redis 通用命令
数据库·redis·缓存
2401_zq136y037 小时前
Flutter for OpenHarmony:从零搭建今日资讯App(二十七)图片缓存的完整方案
flutter·缓存
2401_858286118 小时前
从Redis 8.4.0源码看快速排序(1) 宏函数min和swapcode
c语言·数据库·redis·缓存·快速排序·宏函数
Codeking__9 小时前
Redis——事务
数据库·redis·缓存
Codeking__9 小时前
Redis——认识持久化、RDB、AOF
数据库·redis·缓存
什么都不会的Tristan10 小时前
redis-原理篇-QuickList
数据库·redis·缓存
yuankunliu11 小时前
【redis】2、Redis的Value的常见数据类型以及使用场景
redis·缓存
想摆烂的不会研究的研究生11 小时前
MySQL海量数据深分页优化
数据库·redis·后端·mysql·缓存
曹天骄13 小时前
Cloudflare Worker 性能与缓存命中率测试方案
缓存