Is it possible with std::atomic, make a complex me

2019-09-05 09:13发布

Is it possible to make something like this?

...
class test{
int i;
public:
      test(int k):i(k){};
      void my(){
         cout<<i;
      }
}
atomic<test> kk(0);
kk.test();
...

If this is not possible then how to make a call of function so that it will was atomic?

2条回答
Melony?
2楼-- · 2019-09-05 09:39

You can create std::atomic objects that hold non-numeric objects. The main restriction is that the contained type has to be trivially copyable; loosely speaking (because this is how it's implemented), this means that copying with memcpy is okay, and comparing with memcmp is meaningful. However, it doesn't let you call member functions on the stored object. You have to copy the stored object, do the update, then copy the result back into the atomic object.

查看更多
你好瞎i
3楼-- · 2019-09-05 09:40

The way that std::atomic works is that it uses certain instructions provided by the processor. These instructions are ONLY available for integers of certain sizes (different processors have different limits and rules about what you can and can't do, and in some architectures, the processor architecture may even require the use of a mutex or similar functionality simply to implement std::atomic).

Note also that the purpose of std::atomic is used to ensure that the value is updated atomically across multiple processor cores or multiple processors, which is not typically what you want/can to do with larger data structures.

To achieve atomic operations on other data structures, you will have to use mutex or similar constructs to ensure that the processing is done in an "thread atomic" way (different from "processor atomic").

查看更多
登录 后发表回答