Merge pull request #5 from pkhpkh/refcount-mutex

TOOLS: Add mutex protection for jansson reference counts
This commit is contained in:
Chris Koenig 2015-04-23 11:13:06 -05:00
commit b469f07120
2 changed files with 33 additions and 4 deletions

View File

@ -12,6 +12,8 @@
#include <stdlib.h> /* for size_t */
#include <stdarg.h>
#include <pthread.h>
#include "jansson_config.h"
#ifdef __cplusplus
@ -50,6 +52,7 @@ typedef enum {
typedef struct json_t {
json_type type;
size_t refcount;
pthread_mutex_t refmutex;
} json_t;
#ifndef JANSSON_USING_CMAKE /* disabled if using cmake */
@ -97,8 +100,17 @@ json_t *json_null(void);
static JSON_INLINE
json_t *json_incref(json_t *json)
{
if(json && json->refcount != (size_t)-1)
++json->refcount;
if (json && json->refcount != (size_t)-1)
{
int status = pthread_mutex_lock(&json->refmutex);
if (status == 0)
{
if (json->refcount != (size_t)-1)
++json->refcount;
pthread_mutex_unlock(&json->refmutex);
}
}
return json;
}
@ -108,8 +120,23 @@ void json_delete(json_t *json);
static JSON_INLINE
void json_decref(json_t *json)
{
if(json && json->refcount != (size_t)-1 && --json->refcount == 0)
json_delete(json);
if(json && json->refcount != (size_t)-1)
{
int status = pthread_mutex_lock(&json->refmutex);
if (status == 0)
{
if (json->refcount != (size_t)-1 && --json->refcount == 0)
{
json->refcount = -1;
pthread_mutex_unlock(&json->refmutex);
json_delete(json);
}
else
{
pthread_mutex_unlock(&json->refmutex);
}
}
}
}

View File

@ -41,6 +41,7 @@ static JSON_INLINE void json_init(json_t *json, json_type type)
{
json->type = type;
json->refcount = 1;
pthread_mutex_init(&json->refmutex, 0);
}
@ -946,6 +947,7 @@ void json_delete(json_t *json)
else if(json_is_real(json))
json_delete_real(json_to_real(json));
pthread_mutex_destroy(&json->refmutex);
/* json_delete is not called for true, false or null */
}