Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread safe unique id generation in c++

Tags:

c++

c++11

I was looking for thread safe unique id generation in c++ application life, So I have created following static class.

class Utils {
public :
    static int getUid();
};

int Utils::getUid() {
    static std::atomic<std::uint32_t> uid;
    uid = 0;
    return ++uid;
}

Any suggestion, Is this right approach.

like image 273
Sachin Avatar asked Mar 11 '23 03:03

Sachin


1 Answers

fix it this way:

class Utils {
public :
    static int getUid();
};

int Utils::getUid() {
    static std::atomic<std::uint32_t> uid { 0 };  // <<== initialised
//    uid = 0;    <<== removed
    return ++uid;
}
like image 51
Richard Hodges Avatar answered Mar 21 '23 10:03

Richard Hodges