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

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

简单略有内涵。

相关推荐
Java小混子8 小时前
【Redis】缓存和分布式锁
redis·分布式·缓存
卑微的小鬼9 小时前
如何保证数据库和缓存的一致性?
数据库·缓存
原来是好奇心9 小时前
用户登录Token缓存Redis实践:提升SpringBoot应用性能
spring boot·redis·缓存
wuyunhang12345611 小时前
Redis---事务
数据库·redis·缓存
Tacy021311 小时前
Redis 安装教程
数据库·redis·缓存
用手编织世界13 小时前
redis-缓存-双写一致性
数据库·redis·缓存
想回家的一天1 天前
Go1.25的源码分析-src/runtime/runtime1.go(GMP)
数据库·redis·缓存
Mr. Cao code1 天前
使用Tomcat Clustering和Redis Session Manager实现Session共享
java·linux·运维·redis·缓存·tomcat
你的电影很有趣2 天前
lesson44:Redis 数据库全解析:从数据类型到高级应用
数据库·redis·缓存
kunwen1232 天前
推理还是训练 || KV缓存和CoT技术
缓存·kv缓存·cot技术