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

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

#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->size = size;
    MEMCA_MUTEX(ma->lock);
    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 ;
}

//#define MAMCA_TEST
#ifdef  MEMCA_TEST
#include 
struct memca_s ma = {
    .name = "memca test",
    .size = sizeof(struct memca_s),
    .lock = {0},
    .max  = 256,
    .num  = 0,
    .head = NULL
};

int main(void)
{
    struct memca_s *pma[257];
    memca_init(&ma);

    for (int i = 0; i < 257; ++i) {
        pma[i] = (struct memca_s*)memca_alloc(&ma);
        fprintf(stderr, "%p %p\n", pma[i], *(void**)pma[i]);
    }

    for (int i = 0; i < 257; ++i) {
        *(void **)pma[i] = (uintptr_t) i;
        memca_free(&ma, pma[i]);
        if (i<256)
            fprintf(stderr, "%p %p\n", pma[i], *(void**)pma[i]);
    }
    memca_close(&ma);
}
#endif
#ifndef MEMCA_H
#define MEMCA_H

#include 
#include 

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

你可能感兴趣的:(缓存)