Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with std::atomic and custom structs

Can't seem to do this (see code) for some reason. Looked at documentation, there doesn't seem to be a reason for this not to work...

struct vector {
    float x, y, z;
};
std::atomic<vector> Name = {0};

It says I can't initialize it with an initializer list, and when I go to use it in my code, it says it has no members.

Name.x = 4.f;
Name.y = 2.f * Name.x;
Name.z = 0.1f;
like image 510
vidsac Avatar asked May 04 '26 16:05

vidsac


2 Answers

An instance of std::atomic<vector> isn't an instance of vector. It doesn't have x, y, or z as members. What it does have (conceptually, internally) is an instance of vector. But you can't access it with the . operator because that would break atomicity, which is, like, the point of std::atomic. (This is also why you can't use an initializer list.)

To access the vector stuff, use load() and store():

//atomically load a snapshot of Name
auto name_snapshot = Name.load(); //name_snapshot is a vector instance
name_snapshot.x = 4.f;
name_snapshot.y = 2.f * name_snapshot.x;
name_snapshot.z = 0.1f;
//now atomically store it:
Name.store(name_snapshot);
like image 136
zindorsky Avatar answered May 07 '26 07:05

zindorsky


There is documentation for std::atomic<> here http://en.cppreference.com/w/cpp/atomic/atomic

There are no members x, y, and z on a std::atomic<>.

std::atomic<X> is a type in which the entire X can be replaced atomically, not individual parts of it.

What you probably want is a mutex, since for a structure like name_snapshot, std::atomic will use a mutex in any case. Since there is unlikely to be an atomic instruction available handle an atomic load/store of the entire structure.

like image 22
Richard Hodges Avatar answered May 07 '26 07:05

Richard Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!