Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ atomic for pointers to user defined objects

Tags:

c++11

atomic

Can I have pointers to user defined functions as the template type for atomic variables ? Something like this

class A
{
int d;
public:
 void foo() { cout<<"Hellow wolrd!"; }
};

int main()
{
atomic<A*> ptrA;
//now how to call A::foo() from ptrA ?

}
like image 382
Ram Avatar asked Oct 28 '25 04:10

Ram


1 Answers

You have two ways to call the method:

Method 1:

(*ptrA).foo();

Method 2

A* a = ptrA.load();

a->foo();

I don't know anything about your multi-threaded scenario to advise how best to avoid any pitfalls as you've not provided much information but the second way obviously allows you to guard against certain outcomes. Note also that the load method on std::atomic can accept a number of different memory ordering constraints.

like image 164
keith Avatar answered Oct 30 '25 06:10

keith