From de30721f636ffadd4b08af40a607fc8a4a6f32a3 Mon Sep 17 00:00:00 2001 From: Phillip Howell Date: Thu, 23 Apr 2015 10:29:24 -0500 Subject: [PATCH] TOOLS: Add mutex protection for jansson reference counts --- src/jansson.h | 35 +++++++++++++++++++++++++++++++---- src/value.c | 2 ++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/jansson.h b/src/jansson.h index b980e8c..4917e23 100644 --- a/src/jansson.h +++ b/src/jansson.h @@ -12,6 +12,8 @@ #include /* for size_t */ #include +#include + #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); + } + } + } } diff --git a/src/value.c b/src/value.c index 333d0af..ed0149e 100644 --- a/src/value.c +++ b/src/value.c @@ -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 */ }