Skip to content

Commit

Permalink
Add reference counting to library initialization and deinitialization.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kerilk committed Jun 28, 2023
1 parent 4fe5a9e commit 375fe15
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
20 changes: 14 additions & 6 deletions include/cconfigspace/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -701,17 +701,25 @@ extern const ccs_datum_t ccs_false;
#endif

/**
* The library initialization function. Should be called before any operation
* using the library are performed.
* @return #CCS_RESULT_SUCCESS
* The library initialization function. The library usage is ref counted, so
* this function can be called several times.
* @return #CCS_RESULT_SUCCESS on success
* @return #CCS_RESULT_ERROR_INVALID_VALUE if the library reference count is
* found to be invalid
* @remarks
* This function is thread-safe
*/
extern ccs_result_t
ccs_init();

/**
* The library deinitialization function. Should be called after all operations
* using the library are performed.
* @return #CCS_RESULT_SUCCESS
* The library deinitialization function. When done using the library, should
* be called once for each time #ccs_init was called.
* @return #CCS_RESULT_SUCCESS on success
* @return #CCS_RESULT_ERROR_INVALID_VALUE if the library reference count is
* found to be invalid
* @remarks
* This function is thread-safe
*/
extern ccs_result_t
ccs_fini();
Expand Down
27 changes: 24 additions & 3 deletions src/cconfigspace.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,38 @@ const ccs_version_t ccs_version = {
CCS_VERSION_REVISION, CCS_VERSION_PATCH, CCS_VERSION_MINOR,
CCS_VERSION_MAJOR};

static pthread_mutex_t _ccs_mutex = PTHREAD_MUTEX_INITIALIZER;
static int32_t _ccs_refcount = 0;

ccs_result_t
ccs_init()
{
gsl_rng_env_setup();
return CCS_RESULT_SUCCESS;
ccs_result_t err = CCS_RESULT_SUCCESS;
pthread_mutex_lock(&_ccs_mutex);

CCS_REFUTE_ERR_GOTO(
err, _ccs_refcount < 0 || _ccs_refcount == INT32_MAX,
CCS_RESULT_ERROR_INVALID_VALUE, end);
if (_ccs_refcount == 0)
gsl_rng_env_setup();
_ccs_refcount += 1;
end:
pthread_mutex_unlock(&_ccs_mutex);
return err;
}

ccs_result_t
ccs_fini()
{
return CCS_RESULT_SUCCESS;
ccs_result_t err = CCS_RESULT_SUCCESS;
pthread_mutex_lock(&_ccs_mutex);

CCS_REFUTE_ERR_GOTO(
err, _ccs_refcount < 1, CCS_RESULT_ERROR_INVALID_VALUE, end);
_ccs_refcount -= 1;
end:
pthread_mutex_unlock(&_ccs_mutex);
return err;
}

ccs_version_t
Expand Down

0 comments on commit 375fe15

Please sign in to comment.