Is boost::uuids::random_generator thread safe?
Asked Answered
W

2

6

Consider this function compiling with g++ -std=c++11 (GCC 4.7.2):

boost::uuids::uuid getID()
{
    static boost::uuids::random_generator generator;
    return generator();
}

Is it safe to call getID from multiple threads?

As it is mentioned here the local static object definition at the first line is thread safe according to the C++11 standard. The question is if the call to boost::uuids::random_generator::operator() on the same object generator at the second line is also thread safe. Will the returned UUIDs be unique in the sense they would be in a single thread?

Wisdom answered 19/9, 2013 at 8:59 Comment(0)
C
4

According to this topic random generators are not fully thread safe. I tried using this class in a way similar to your implementation. I get a crash every several hours and the generator sometimes returns "zero" uuids, something like 0000-0000-000 - you get the idea. Although it is not documented, I would assume that this class is not thread safe. You have to either create a generator instance every time you generate uuid, or you can use mutex to make the call to getID() thread safe, or you can create one instance of uuid generator per thread. All options should work fine.

Caveman answered 28/5, 2014 at 9:8 Comment(2)
Creating an instance of the uuid generator every time you need a new uuid is a wrong advice, as far as I know.Extracanonical
I'd say so too, because there seems to be a possibility of hash collision if you have two different generators.Gq
H
2

boost::uuids::random_generator is not thread safe (it cannot be shared without synchronization) as stated in the documentation for boost Uuid library:

Classes are as thread-safe as an int. That is an instance can not be shared between threads without proper synchronization.

Hypostasize answered 13/5, 2019 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.