Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boost::uuids::random_generator thread safe?

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?

like image 810
Vahagn Avatar asked Sep 19 '13 08:09

Vahagn


2 Answers

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.

like image 119
user3323559 Avatar answered Sep 20 '22 07:09

user3323559


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.

like image 41
LVK Avatar answered Sep 22 '22 07:09

LVK