Matt Pennington Matt Pennington - 1 month ago 11
C++ Question

Misunderstanding of atomic structs and pointers

My first question is: Is there any way to access the members of struct in an

atomic<struct>
object?
For example, I get the compiler error:

struct std::atomic<node>’ has no member named ‘data’ a.data = 0;


in this segment

struct node{
int data;
node* next;
};

int main(){
atomic<node> a;
a.data = 0;
}


I can work around it by creating a temporary node like so:

atomic<node> a;
node temp;
temp.data = 0;
a.store(temp);


but this doesn't seem very elegant.

The second question is, what if I have a pointer to an atomic object? Is there anyway to access the members of the node directly? Obviously the following does not compile, how would I change this to store 0 in the value of the node at b?

atomic<node> b = new node;
b->data = 0;


This is a solution I've found, but again, is there a more elegant way of doing this??

atomic<node> *b;
node temp;
temp.data = 0;
b->store(&temp);


And lastly, what is the difference between
atomic<node*>
and
atomic<node>*

Answer

this [workaround] doesn't seem very elegant.

std::atomic<T> cannot make arbitrary operations atomic: only loading and storing the data is supported. That is why your "workaround" is actually the way to deal with atomic objects: you prepare the new node value in any way that you like, and then atomically set it into an atomic<node> variable.

what if I have a pointer to an atomic object? Is there anyway to access the members of the node directly?

Accessing the content of a node through a pointer would not be atomic as well: since std::atomic<T> can guarantee only loading and storing its value to be atomic, it does not let you access T's members without making an explicit copy. This is a good thing, because it prevents readers of the code from getting a false impression that the access to T's internals is somehow atomic.

what is the difference between atomic<node*> and atomic<node>*

In the firs case, the atomic object stores a pointer, which can be accessed atomically (i.e. you can re-point this pointer to a new node atomically). In the second case, the atomic object stores the value that can be accessed atomically, meaning that you can read and write the entire node atomically.

Comments