Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

please see bug 2312 #2

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
21 changes: 19 additions & 2 deletions cache.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <inttypes.h>

#ifndef NDEBUG
Expand All @@ -16,6 +18,16 @@ int cache_error = 0;

const int initial_pool_size = 64;

#ifndef NDEBUG
static bool inFreeList(cache_t *cache, void *object) {
bool rv = false;
for (int i = 0; i < cache->freecurr; i++) {
rv |= cache->ptr[i] == object;
}
return rv;
}
#endif

cache_t* cache_create(const char *name, size_t bufsize, size_t align,
cache_constructor_t* constructor,
cache_destructor_t* destructor) {
Expand Down Expand Up @@ -74,6 +86,7 @@ void* cache_alloc(cache_t *cache) {
if (cache->freecurr > 0) {
ret = cache->ptr[--cache->freecurr];
object = get_object(ret);
assert(!inFreeList(cache, ret));
} else {
object = ret = malloc(cache->bufsize);
if (ret != NULL) {
Expand Down Expand Up @@ -102,7 +115,8 @@ void* cache_alloc(cache_t *cache) {
return object;
}

void cache_free(cache_t *cache, void *ptr) {
void cache_free(cache_t *cache, void *object) {
void *ptr = object;
pthread_mutex_lock(&cache->mutex);

#ifndef NDEBUG
Expand All @@ -124,8 +138,10 @@ void cache_free(cache_t *cache, void *ptr) {
}
ptr = pre;
#endif
assert(!inFreeList(cache, ptr));
if (cache->freecurr < cache->freetotal) {
cache->ptr[cache->freecurr++] = ptr;
assert(inFreeList(cache, ptr));
} else {
/* try to enlarge free connections array */
size_t newtotal = cache->freetotal * 2;
Expand All @@ -134,12 +150,13 @@ void cache_free(cache_t *cache, void *ptr) {
cache->freetotal = newtotal;
cache->ptr = new_free;
cache->ptr[cache->freecurr++] = ptr;
assert(inFreeList(cache, ptr));
} else {
if (cache->destructor) {
cache->destructor(ptr, NULL);
}
free(ptr);

assert(!inFreeList(cache, ptr));
}
}
pthread_mutex_unlock(&cache->mutex);
Expand Down
Loading