Reputation: 74
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;
Upvotes: 3
Views: 2537
Reputation: 74
It's Name._My_val.x, Name._My_val.y, Name._My_val.z
not Name.x, Name.y, Name.z
Why it is no one told me this is beyond me, but whatever.
Upvotes: -3
Reputation: 69892
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.
Upvotes: 2
Reputation: 1592
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);
Upvotes: 4