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

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

简单略有内涵。

相关推荐
Alan_6914 小时前
商品详情优化三板斧-拆分-多级缓存-GC调参
后端·缓存
難釋懷7 小时前
Nginx-proxy缓存断点续传缓存 range
运维·nginx·缓存
杨运交8 小时前
[053][核心模块]Java枚举缓存与ORM集成实践
java·开发语言·缓存
liulilittle12 小时前
LLM推理中的KV缓存与跨请求前缀复用:机制、条件与提示词
缓存·ai·llm
智码看视界13 小时前
Day33-数据层 × 中间件AI化篇:Redis缓存经典问题-击穿、穿透、雪崩的终极解决方案
数据库·redis·缓存·中间件·穿透·雪崩·击穿
難釋懷13 小时前
Nginx-proxy缓存清理
运维·nginx·缓存
咩咩啃树皮1 天前
第43篇:Vue3计算属性(computed)完全精讲——缓存机制、依赖计算、业务最优解
前端·vue.js·缓存
海兰1 天前
【高速缓存】RedisVL 存储类型选择指南:Hash 与 JSON
人工智能·redis·算法·缓存·json·哈希算法
海兰2 天前
【高速缓存】RedisVL 索引迁移指南:安全演进索引结构
前端·数据库·redis·安全·缓存·bootstrap
YOU OU2 天前
Redis事务
数据库·redis·缓存