How to implement a static connection by using Aerospike C client

I’m using C aerospike client library. I have to connect to the aerospike cluster several times in multi process. So I would like to implement a singleton pattern by C. Now I implemented the logic like below. It is possible to connect to the aerospike cluster, however, it does not make a singleton. Could you tell me how to implement a singleton pattern by C?

Like singleton function

static aerospike aero;
aerospike get_instance()
    {
        as_error err;
        as_config cfg;
        as_config_init(&cfg);
        as_config_add_hosts(&cfg, "aerospike", 3000);
        aerospike_init(&aero, &cfg);
        if (aerospike_connect(&aero, &err) != AEROSPIKE_OK) {
            ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, "ERROR: failed to connect aerospike returned %d - %s \n", err.code, err.message);
            aerospike_destroy(&aero);
            return;
        }
        return aero;
    }

A caller side

aerospike aero;
aero = get_instance();

Do you intend to share the aerospike instance between threads or processes?

Sharing instances between processes would require implementing shared memory which can get complicated.

There are two ways to initialize a single aerospike instance which is shared between threads.

  1. Define a global aerospike instance and initialize this instance once at startup before other threads are created. Then, reference the global aerospike instance when the other threads are created. The C client benchmarks implements this method.

  2. If it’s not possible to initialize the global aerospike instance before creating other threads, you can apply a lock in get_instance() and return existing global instance if it was already initiailized.

static aerospike aero;
static bool aero_initialized = false;
static pthread_mutex_t aero_lock = PTHREAD_MUTEX_INITIALIZER;

aerospike* get_instance()
{
    pthread_mutex_lock(&aero_lock);

    if (aero_initialized) {
        pthread_mutex_unlock(&aero_lock);
        return &aero;
    }

    as_error err;
    as_config cfg;
    as_config_init(&cfg);
    as_config_add_hosts(&cfg, "aerospike", 3000);
    aerospike_init(&aero, &cfg);
    if (aerospike_connect(&aero, &err) != AEROSPIKE_OK) {
        ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, "ERROR: failed to connect     aerospike returned %d - %s \n", err.code, err.message);
        aerospike_destroy(&aero);
	pthread_mutex_unlock(&aero_lock);
        return NULL;
    }
    aero_initialized = true;
    pthread_mutex_unlock(&aero_lock);
    return &aero;
}

Caller side:

aerospike* as = get_instance();

It worked well. Thank you very much.

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.