0

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] );

}
Community
  • 1
  • 1
Josh
  • 363
  • 3
  • 14

2 Answers2

2

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

john
  • 71,156
  • 4
  • 49
  • 68
  • Ah right, that fixes the problem. I was under the impression that initializing static mutexes at runtime was bad style. Thank you for pointing out my mistake. – Josh Nov 28 '13 at 07:32
1

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.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550