Skip to content

Commit

Permalink
Modernisation: Protect iterator's init() with a mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
joobog committed Oct 17, 2024
1 parent 423521b commit b490cfc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 36 deletions.
35 changes: 34 additions & 1 deletion src/grib_iterator_class.cc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,34 @@
/* This file is generated by ./make_class.pl */
#include "grib_iterator_class.h"

#if GRIB_PTHREADS
static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

static void init_mutex()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
#elif GRIB_OMP_THREADS
static int once = 0;
static omp_nest_lock_t mutex1;

static void init_mutex()
{
GRIB_OMP_CRITICAL(lock_grib_accessor_class_c)
{
if (once == 0) {
omp_init_nest_lock(&mutex1);
once = 1;
}
}
}
#endif

struct table_entry
{
const char* type;
Expand All @@ -44,7 +72,12 @@ eccodes::grib::geo::Iterator* grib_iterator_factory(grib_handle* h, grib_argumen
eccodes::grib::geo::Iterator* builder = *(table[i].iterator);
eccodes::grib::geo::Iterator* it = builder->create();
it->flags_ = flags;
*error = it->init(h, args);

GRIB_MUTEX_INIT_ONCE(&once, &init_mutex);
GRIB_MUTEX_LOCK(&mutex);
*error = it->init(h, args);
GRIB_MUTEX_UNLOCK(&mutex);

if (*error == GRIB_SUCCESS)
return it;
grib_context_log(h->context, GRIB_LOG_ERROR, "Geoiterator factory: Error instantiating iterator %s (%s)",
Expand Down
36 changes: 1 addition & 35 deletions src/iterator/grib_iterator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,50 +18,16 @@ namespace eccodes {
namespace grib {
namespace geo {

#if GRIB_PTHREADS
static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

static void init_mutex()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
#elif GRIB_OMP_THREADS
static int once = 0;
static omp_nest_lock_t mutex;

static void init_mutex()
{
GRIB_OMP_CRITICAL(lock_iterator_c)
{
if (once == 0) {
omp_init_nest_lock(&mutex);
once = 1;
}
}
}
#endif


int Iterator::init(grib_handle* h, grib_arguments* args)
{
int r = 0;
h_ = h;
//GRIB_MUTEX_INIT_ONCE(&once, &init_mutex);
//GRIB_MUTEX_LOCK(&mutex);
//r = init_iterator(this, i, h, args);
//GRIB_MUTEX_UNLOCK(&mutex);
return r;
return GRIB_SUCCESS;
}

/* For this one, ALL destroy are called */
int Iterator::destroy()
{
//grib_context_free(context_, this);
delete context_;
delete this;
return GRIB_SUCCESS;
Expand Down

0 comments on commit b490cfc

Please sign in to comment.