gpt4 book ai didi

c++ - 在 C++ 中初始化 pthread 互斥的静态数组

转载 作者:行者123 更新时间:2023-11-28 00:37:44 25 4
gpt4 key购买 nike

在下面的代码中,我收到一个错误,指出 acc_locks 是 add_to_balance 函数中 undefined reference 。 acc_locks 是 pthread_mutex_t 的数组。

我认为这个错误是由于在构造函数被调用之前互斥量没有被初始化。

我想用 PTHREAD_MUTEX_INITIALIZER 初始化它们,但我不知道如何在不将其写出 100 次的情况下完成此操作。 (我不会出于原则这样做)

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

本文,Static pthreads mutex initialization ,描述了如何使用 P99_DUPL 在 C 中完成此操作。我不能在 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] );

}

最佳答案

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

pthread_mutex_t AccountMonitor::acc_locks[num_accounts];

到 AccountMonitor.cpp

关于c++ - 在 C++ 中初始化 pthread 互斥的静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20259300/

25 4 0