I have two questions about atomics:
1) Is the following code guaranteed to return consecutive, monotonically increasing sequences without duplicates in a multi-threaded setup?
#include <atomic>
struct AtomicCounter {
std::atomic<int> value;
AtomicCounter() : value( 0 ) {}
int getNextSequence(){
return ++value;
}
};
2) Is there a simpler way to initialize? None of these worked:
std::atomic<int> value ( 0 ) ;
std::atomic<int> value { 0 } ;
std::atomic<int> value=0;
Thanks in advance
atomic<int> value {0};
is the right syntax (demo). However, not all C++ compilers provide support for non-static data member initializers of C++11, so using the initializer list of C++98 may be the only way available to you at the moment.Here is a link to C++11 feature lists implemented by various compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With