I am new to concurrent programming and learning it in C++. While learning std::condition_variable
, I implemented a simple class ManageTransaction
given below. Defining _cv
, _mutex
, and _balance
as private members of the class causes a segmentation fault. Defining them globally doesn't cause it.
#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;
}
Q1。在类中定义成员时,为什么会发生分段错误?
Q2。通过将变量定义为类的成员,是否有避免分段错误的方法?
您的shared_ptr尚未初始化,并将具有空值。因此,一旦函数尝试访问私有成员数据,您就会遇到各种访问冲突。在尝试使用指针之前,请考虑使用std :: make_shared分配指针。