C++多线程程序:变量定义为类成员的隔离错误

C++ multi-thread program: Segementation fault with variables defined as class members

本文关键字:成员 隔离 错误 定义 多线程 程序 变量 C++      更新时间:2023-10-16

我是并发编程的新手,并在C++学习它。在学习std::condition_variable的过程中,我实现了一个简单的类ManageTransaction下面给出的。将_cv_mutex_balance定义为类的私有成员会导致分段错误。全局定义它们不会导致它。

#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <condition_variable>
std::condition_variable _cv;
std::mutex _mutex;
int _balance = 0;
class ManageTransaction {
public:
void addMoney(int credit_value) {
std::lock_guard<std::mutex> lock(_mutex);
std::cout << "t2, addMoney: _mutex is locked! n";
_balance += credit_value;
std::cout << credit_value << " is added and the current balance is " << _balance << std::endl;
_cv.notify_one();
std::cout << "t2, addMoney: _mutex is unlocked! n";
}
void withdrawMoney(int debit_value) {
std::unique_lock<std::mutex> lock(_mutex);
std::cout << "t1, withdrawMoney: _mutex is locked! n";
std::this_thread::sleep_for(std::chrono::seconds(1)); // simulate work
_cv.wait(lock, [this] {return _balance == 0 ? false : true;});
std::cout << "t1, withdrawMoney: wait is finished and _mutex is unlocked! n";
_balance -= debit_value;
std::cout << "t1, withdrawMoney: " << debit_value << " is deducted and the current balance is " << _balance << std::endl;
}
// private:
// std::condition_variable _cv;
// std::mutex _mutex;
// int _balance = 0;
};
int main() {
std::shared_ptr<ManageTransaction> t;
std::thread t1(&ManageTransaction::withdrawMoney, t, 500);
std::thread t2(&ManageTransaction::addMoney, t, 500);
t1.join();
t2.join();
return 0;
}

问题 1.为什么在类中定义成员时会出现分段错误?

问题 2.有没有办法通过将变量定义为类的成员来避免分段错误?

您的shared_ptr未初始化,将具有空值。因此,一旦函数尝试访问私有成员数据,您就会收到各种访问冲突。在尝试使用指针之前,请考虑使用 std::make_shared 分配指针。或者更好的是,取消shared_ptr;在堆栈上声明变量并传递引用。