Josh
Josh

Reputation: 383

Initializing a static array of pthread mutexes in C++

In the following code I am recieving an error that acc_locks is an undefined reference in the add_to_balance function. acc_locks is an array of pthread_mutex_t.

I think the error is due to the mutexes not being initialized until the constructor is called.

I would like to initialize them with PTHREAD_MUTEX_INITIALIZER, but I don't know how to accomplish this without writing it out 100 times. (Which I won't do out of principle)

acc_locks = {PTHREAD_MUTEX_INITIALIZER, ... } //100 times

This article, Static pthreads mutex initialization, describes how this can be done in C using P99_DUPL. I can't use C99 w/ C++. Is there a similar duplication macro for C++? Am I trying to solve the wrong problem?

//AccountMonitor.h
#include <pthread.h>

static const unsigned char num_accounts = 100;

class AccountMonitor{
  private:
    static float balance[ num_accounts];
    static pthread_mutex_t acc_locks[ num_accounts];
  public:
    AccountMonitor();
    void add_to_balance(int acc,float v);

};


//AccountMonitor.cpp
#include "AccountMonitor.h"

float AccountMonitor::balance[ num_accounts] = {0.0};

AccountMonitor::AccountMonitor(){
    for (int i=0; i<num_accounts; i++){ 
        pthread_mutex_init( &acc_locks[i], NULL );
    }
}

void AccountMonitor::add_to_balance(int acc, float v){
    int index = acc - 1;

    pthread_mutex_lock( &acc_locks[ index] );
    balance[ index] += v;
    pthread_mutex_unlock ( &acc_locks[index] );

}

Upvotes: 0

Views: 4657

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

You can solve this by putting the mutexes in a separate class (as a non-static member) and then have a static instance of that class in AccountMonitor. Then the wrapper-class containing the mutexes can initialize them in its constructor.

Upvotes: 1

john
john

Reputation: 87959

You might be aware of this (I think your question is a bit unclear) but the error you have is due to you not defining acc_locks. It's strange because you did define balance, but not acc_locks. Just add

pthread_mutex_t AccountMonitor::acc_locks[num_accounts];

to AccountMonitor.cpp

Upvotes: 2

Related Questions