c++ - 使用 PThreads 的全局列表访问 - 指针问题?

标签 c++ c pointers pthreads

我们正在做一个项目,使用线程和互斥锁来模拟一群客户访问不同或相同的银行账户。我几乎没有 C/C++ 经验,我认为这个问题与指针相关。基本上我有一个 Client 对象,它包含一个交易列表和一个帐户列表,它作为参数传递给 pthread,在那里它被发送到处理方法。

class Client{
public:
    list<Transaction> transactions;
    list<Account>* accounts;
    Client(list<Transaction>, list<Account>);
};

Client::Client(list<Transaction> a, list<Account> b){
transactions = a;
accounts = &b;
}

extern "C"
{
void* RunTransactions(void* arg)
{
    Client* c = static_cast<Client*>(arg);

    // while(!(*c).transactions.empty()){
        // cout << "HERE" << endl;
    // }

    cout << "Thread Before: ";
    (*(*c).accounts).front().Print();

    (*(*c).accounts).front().balance -= 25;
    (*(*c).accounts).front().balance -= 25;
    (*(*c).accounts).front().balance -= 25;

    cout << "Thread After: ";
    (*(*c).accounts).front().Print();

    // list<Transaction>* trans = static_cast<list<Transaction>*>(arg);
    // Transaction t = trans->front();
    // t.Print();

    // Test* t = static_cast<Test*>(arg);

    // (*t).Increase();
    // cout << "Thread - " << t->x << endl;

    return 0;
}
}

int main( ){

list<Account> accounts;

cout << "Accounts: ";
cin >> NumAccts;

for(long i = 0; i < NumAccts; i++){
    long tempBalance;
    cout << "Balance for Account " << i << ": ";
    cin >> tempBalance;

    accounts.push_back(Account(i, tempBalance));
}

//Test Input
pthread_t t1;
list<Transaction> tempTrans;
tempTrans.push_back(Transaction(0, 1, 100));
tempTrans.push_back(Transaction(1, 0, 50));
tempTrans.push_back(Transaction(2, 1, 222));

Client c = Client(tempTrans, accounts);

cout << "Main Before: ";
accounts.front().Print();

pthread_create(&t1, NULL, RunTransactions, &c);

pthread_join(t1, NULL);

cout << "Main After: ";
accounts.front().Print();


return 0;
}

我不明白的是我应该如何让我的线程都可以访问在 main 中创建的帐户列表?现在,每当我对从客户端中提取的帐户列表进行任何操作时,它都会在线程中进行更改,但在加入后我看不到主帐户列表中的更改。同样,我认为这与我在 Client 对象或 main 或 RunTransactions 中传递或访问帐户的方式有关?任何建议将不胜感激!

最佳答案

Client::Client(list<Transaction> a, list<Account> b) {

b 是传入列表的拷贝,几乎肯定会在堆栈上传递。一旦构造函数返回,您的指针可能无效。

您最好将客户的帐户 设为实际列表而不是指向列表的指针。你真的不想让你的对象持有指向不是堆分配的东西的指针,或者其他人可以访问的东西。那就是疯狂。

关于c++ - 使用 PThreads 的全局列表访问 - 指针问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8434008/

相关文章:

c++ - 如何正确标记字符串

c++ - 将 float float/double 的余数转换为 int

c++ - 如何在 C++ 中创建一个简单的 COM 组件

c++ - 我可以在 Vista 和 Windows 7 下以用户模式获得对原始磁盘扇区的写访问权限吗?

c++ - 指针数组为什么会出现段错误?

c++ - netbeans ide 7.1.1 是否支持 c++11

c++ - 使用带有 C 函数指针的 C++ 类成员函数

c - 如何检测数组中的重复项并打印非重复项?

c++ - 将二维数组转换为指针到指针

c - 指向二维动态数组指针的指针