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?
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.
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.
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