C++多线程程序:变量定义为类成员的隔离错误
C++ multi-thread program: Segementation fault with variables defined as class members
我是并发编程的新手,并在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;在堆栈上声明变量并传递引用。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- C++多线程程序:变量定义为类成员的隔离错误
- 尝试访问标头声明成员时出现隔离错误
- 调用成员>函数(this);在析构函数中导致隔离错误
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- 推送到成员向量时的隔离错误
- 隔离类的并发/非并发访问数据成员
- 删除与另一个成员相等的链表成员的嵌套循环中断.将问题隔离到一行