Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consecutive, distinct sequences in C++ 11 using Atomic

Tags:

c++

c++11

atomic

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

like image 933
FirstNameSurName Avatar asked Jan 10 '23 15:01

FirstNameSurName


1 Answers

  1. Yes, you will get a sequence without gaps or duplicates, even in concurrent environments. The "monotonically increasing" implies sequencing on the part of the caller - in the sense that to define what comes before and what comes after you need to define in what sequence the events take place. For example, there is no guarantee that the thread that initiates the call first among several concurrent threads would necessarily get a smaller value.
  2. The 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.

like image 139
Sergey Kalinichenko Avatar answered Jan 18 '23 11:01

Sergey Kalinichenko