【问题标题】:Initializing a static array of pthread mutexes in C++在 C++ 中初始化 pthread 互斥体的静态数组
【发布时间】:2013-11-28 06:37:11
【问题描述】:

在以下代码中,我收到一个错误,即 acc_locks 是 add_to_balance 函数中的未定义引用。 acc_locks 是一个 pthread_mutex_t 数组。

我认为错误是由于在调用构造函数之前未初始化互斥锁。

我想用 PTHREAD_MUTEX_INITIALIZER 来初始化它们,但是如果不写 100 次我不知道如何完成。 (原则上我不会这样做)

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

这篇文章,Static pthreads mutex initialization,描述了如何在 C 中使用 P99_DUPL 完成此操作。我不能使用带有 C++ 的 C99。 C++ 是否有类似的复制宏?我是在尝试解决错误的问题吗?

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

}

【问题讨论】:

    标签: c++ pthreads


    【解决方案1】:

    您可能已经意识到这一点(我认为您的问题有点不清楚),但您遇到的错误是由于您没有定义 acc_locks。这很奇怪,因为您确实定义了平衡,但没有定义 acc_locks。只需添加

    pthread_mutex_t AccountMonitor::acc_locks[num_accounts];
    

    到 AccountMonitor.cpp

    【讨论】:

    • 嗯,这解决了问题。我的印象是在运行时初始化静态互斥锁是不好的风格。感谢您指出我的错误。
    【解决方案2】:

    您可以通过将互斥锁放在单独的类中(作为非静态成员)来解决这个问题,然后在AccountMonitor 中拥有该类的静态实例。然后包含互斥体的包装类可以在其构造函数中初始化它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-07
      • 2011-07-05
      • 2020-03-23
      • 1970-01-01
      • 2021-09-01
      • 2021-06-11
      • 1970-01-01
      • 2015-05-31
      相关资源
      最近更新 更多