implemented proper refcounting using atomic operations
This commit is contained in:
@@ -25,6 +25,7 @@
|
||||
#include <time.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
@@ -198,6 +199,43 @@ void *clalloc(void * pointer, size_t size)
|
||||
return (data);
|
||||
}
|
||||
|
||||
/**
|
||||
* We use a single mutex for all refcount variables. This
|
||||
* is not optimal for performance, but the critical section
|
||||
* is not that long...
|
||||
* TODO: Consider to include a mutex in each refcount_t variable.
|
||||
*/
|
||||
static pthread_mutex_t ref_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
/**
|
||||
* Described in header.
|
||||
*
|
||||
* TODO: May be implemented with atomic CPU instructions
|
||||
* instead of a mutex.
|
||||
*/
|
||||
void ref_get(refcount_t *ref)
|
||||
{
|
||||
pthread_mutex_lock(&ref_mutex);
|
||||
(*ref)++;
|
||||
pthread_mutex_unlock(&ref_mutex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Described in header.
|
||||
*
|
||||
* TODO: May be implemented with atomic CPU instructions
|
||||
* instead of a mutex.
|
||||
*/
|
||||
bool ref_put(refcount_t *ref)
|
||||
{
|
||||
bool more_refs;
|
||||
|
||||
pthread_mutex_lock(&ref_mutex);
|
||||
more_refs = --(*ref);
|
||||
pthread_mutex_unlock(&ref_mutex);
|
||||
return !more_refs;
|
||||
}
|
||||
|
||||
/*
|
||||
* Names of the months used by timetoa()
|
||||
*/
|
||||
|
||||
@@ -200,6 +200,32 @@ void chunk_to_hex(char *buf, size_t buflen, chunk_t chunk);
|
||||
*/
|
||||
void *clalloc(void *pointer, size_t size);
|
||||
|
||||
/**
|
||||
* Special type to count references
|
||||
*/
|
||||
typedef volatile u_int refcount_t;
|
||||
|
||||
/**
|
||||
* @brief Get a new reference.
|
||||
*
|
||||
* Increments the reference counter atomic.
|
||||
*
|
||||
* @param ref pointer to ref counter
|
||||
*/
|
||||
void ref_get(refcount_t *ref);
|
||||
|
||||
/**
|
||||
* @brief Put back a unused reference.
|
||||
*
|
||||
* Decrements the reference counter atomic and
|
||||
* says if more references available.
|
||||
*
|
||||
* @param ref pointer to ref counter
|
||||
* @return TRUE if no more references counted
|
||||
*/
|
||||
bool ref_put(refcount_t *ref);
|
||||
|
||||
|
||||
#define UNDEFINED_TIME 0
|
||||
#define TIMETOA_BUF 30
|
||||
|
||||
|
||||
Reference in New Issue
Block a user