简体   繁体   English

C ++ std :: atomic联合

[英]C++ std::atomic union

How do I set a union to be atomic using std::atomic? 如何使用std :: atomic将并集设置为atomic? Or do I have to declare the members of the union to be atomic instead? 还是我必须声明工会的成员是原子的?

typedef union {
    int integer;
    float flt;
    double dbl;
    int *intArray;
    float *floatArray;
    unsigned char *byteArray;
} ValueUnion;

class FooClass {
public:
    std::atomic<ValueUnion> value;

}; 

Access to the union gives an error: 访问联合会出现错误:

foo->value.floatArray = NULL;

error: no member named 'floatArray' in 'std::__1::atomic<ValueUnion>'
                    foo->value.floatArray = NULL;

Do I need to do something like: 我需要做类似的事情吗?

typedef union {
    std::atomic<int> integer;
    std::atomic<float> flt;
    std::atomic<double> dbl;
    std::atomic<int*> *intArray;
    std::atomic<float*> *floatArray;
    std::atomic<unsigned char*> *byteArray;
} ValueUnion;

and declare the member variable value to be as below? 并声明成员变量值如下?

class FooClass {
public:
    ValueUnion value;

}; 

I suppose you'll have to use atomic memory access and writes: 我想您必须使用原子内存访问并编写:

typedef union {
    int integer;
    float flt;
    double dbl;
    int *intArray;
    float *floatArray;
    unsigned char *byteArray;
} ValueUnion;

class FooClass {
public:
    std::atomic<ValueUnion> value;

}; 
int main()
{
    FooClass obj;
    ValueUnion temp = obj.value.load();
    temp.floatArray = NULL;
    obj.value.store(temp); 
}

notice that this doesn't guarantee that the load/modify/store sequence is atomic. 注意,这不能保证load/modify/store序列是原子的。 You'll have to deal with the safety of those instructions yourself (eg mutex ) 您必须自己处理这些说明的安全性(例如互斥体

It depends what you want to do with it. 这取决于您要如何处理。 For example, to store a value into an atomic union: 例如,要将值存储到原子联合中:

foo->value = []{ ValueUnion u; u.floatArray = NULL; return u; }();

or 要么

foo->value.store([]{ ValueUnion u; u.floatArray = NULL; return u; }());

If you want to be able to perform lock-free atomic arithmetic (eg atomic increment) on the contained values then you will need to go for your second design (a union of atomics). 如果您希望能够对所包含的值执行无锁原子算术(例如原子增量),那么您将需要进行第二个设计(原子的并集)。

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

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