我有一个类,我想在不同的线程中使用它,我想我可以使用std :: atomic这样的:
classs A
{
int x;
public:
A()
{
x=0;
}
void Add()
{
x++;
}
void Sub()
{
x--;
}
};
在我的代码中:
std::atomic<A> a;
并在不同的线程:
a.Add();
和
a.Sub();
但是当我收到错误,a.Add()不知道.我该如何实现?
有什么更好的办法吗?
编辑1
请注意,这是一个示例,我想要的是确保访问类A是线程安全的,所以我不能使用
std::atomic<int> x;
如何使用std :: atomic来使线程安全
解决方法
您需要使x属性为原子,而不是您的整个类,如下所示:
class A
{
std::atomic<int> x;
public:
A() {
x=0;
}
void Add() {
x++;
}
void Sub() {
x--;
}
};
您在原始代码中获得的错误是完全正常的:除非您为std :: atomic< A>提供专业化,否则没有std :: atomic< A> :: Add方法(请参阅here).
参考你的编辑:通过使用它作为std :: atomic的模板参数,你不能神奇地使你的类线程安全.为了使其线程安全,您可以将其属性原子化(如上所述,并提供标准库为其提供专业化),或使用互斥锁自动锁定资源.请参阅mutex标题.例如:
class A
{
std::atomic<int> x;
std::vector<int> v;
std::mutex mtx;
void Add() {
x++;
}
void Sub() {
x--;
}
/* Example method to protect a vector */
void complexMethod() {
mtx.lock();
// Do whatever complex operation you need here
// - access element
// - erase element
// - etc ...
mtx.unlock();
}
/*
** Another example using std::lock_guard,as suggested in comments
** if you don't need to manually manipulate the mutex
*/
void complexMethod2() {
std::lock_guard<std::mutex> guard(mtx);
// access,erase,add elements ...
}
};