1

I am trying to understand std::atomic types and atomic operations. Below is my code:

#include <atomic>
#include <iostream>

class A
{
public:
    int x;
    void Show() {}
};

int main()
{
    std::atomic<A> fooA;
    // fooA.Show(); -- gives me std::atomic<A> has no member Show()
}

What are the atomic operations we can do when we define a user type - like Mtype.load() etc - how can we use Mtype with load() atomic operations - where load atomically obtains the value of the atomic object?

Programmer
  • 8,303
  • 23
  • 78
  • 162
  • 2
    You cannot call the member functions directly on the atomic. You have to first get the value. You have to use either `std::atomic_load` or a member function `load`. See [docs](https://en.cppreference.com/w/cpp/atomic/atomic) – Croolman Sep 01 '20 at 06:40

1 Answers1

0

An atomic operation only makes sense whereby you can perform a compare-and-swap exchange on the given data type. This means the data must be "trivially copyable".

For anything bigger than an integral type, you're better off using a mutex to protect the elements of a structure which are accessible from multiple threads - "shared mutable state".

For more information see this post: How to use std::atomic<> effectively for non-primitive types?

Den-Jason
  • 2,395
  • 1
  • 22
  • 17