> Q. Is it because the type is not atomic that the set functions are not atomic?
No. Even if individual operations on two objects are atomic, a compound operation involving both need not be atomic.
With
1 2 3 4 5
|
void set( int value ) {
type = int_type ; // type is an atomic object
int_value = value ; // int_value is also an atomic object
}
|
For instance, we may get this sequence of operations:
1. Thread a atomically stores int_type in type
2. Thread b atomically stores
bool_type in type
3. Thread b atomically stores true in bit
4. Thread a atomically stores
value in int_value
> Is mutex is slower than an atomic type or is it slower because both the type and the bit/int_value are being guarded?
Typically, an atomic object which is lock free is faster than an object guarded by a mutex.
http://en.cppreference.com/w/cpp/atomic/atomic/is_lock_free
More information:
http://www.cplusplus.com/forum/general/194170/#msg933840
Ckeck if
Sensor_packet::data_ is lock free:
http://coliru.stacked-crooked.com/a/e6c67c62223980cd
http://rextester.com/MBGL22613
> Can you suggest an implementation to protect a serial port?
The requirement to create the atomic type
std::atomic<serial_port> is that the type
serial_port is
TriviallyCopyable
Note: since copying serial ports would not be semantically correct, you would have to guard it indirectly through a
TriviallyCopyable wrapper: for instance through,
std::atomic< std::reference_wrapper<serial_port> >
> What is the reason for the static_assert ? Won't the default destructor suffice?
If a union contains a non-static data member with a non-trivial special member function (default constructor, copy/move constructor, copy/move assignment, or destructor), that function is deleted by default in the union and needs to be defined explicitly by the programmer.
http://en.cppreference.com/w/cpp/language/union |