简体   繁体   English

boost :: uuids :: random_generator线程是否安全?

[英]Is boost::uuids::random_generator thread safe?

Consider this function compiling with g++ -std=c++11 (GCC 4.7.2): 考虑使用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? 从多个线程调用getID是否安全?

As it is mentioned here the local static object definition at the first line is thread safe according to the C++11 standard. 正如这里提到的根据C ++ 11标准,第一行的本地静态对象定义是线程安全的。 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. 问题是如果在第二行的同一对象generator上调用boost::uuids::random_generator::operator()也是线程安全的。 Will the returned UUIDs be unique in the sense they would be in a single thread? 返回的UUID是否会在单个线程中是唯一的?

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. 我每隔几个小时发生一次撞击,发电机有时会返回“零”uuids,比如0000-0000-000 - 你明白了。 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. 您必须在每次生成uuid时创建生成器实例,或者您可以使用mutex来调用getID()线程安全,或者您可以为每个线程创建一个uuid生成器实例。 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: boost::uuids::random_generator不是线程安全的(如果没有同步就无法共享),如boost Uuid库文档中所述:

Classes are as thread-safe as an int. 类与int一样是线程安全的。 That is an instance can not be shared between threads without proper synchronization. 这是没有正确同步的线程之间无法共享的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM