How to use std::atomic<>

后端 未结 4 1775
南笙
南笙 2021-01-30 09:25

I have a class that I want to use in different threads and I think I may be able to use std::atomic this way:

class A
{
    int x;

public:
    A()
         


        
4条回答
  •  伪装坚强ぢ
    2021-01-30 09:54

    I think the problem with the answers above is that they don't explain what I think is, at a minimum, an ambiguity in the question, and most likely, a common threaded development fallacy.

    You can't make an object "atomic" because the interval between two functions (first "read x" and then later "write x") will cause a race with other uses. If you think you need an "atomic" object, then you need to carefully design the API and member functions to expose now to begin and commit updates to the object.

    If all you mean by "atomic" is "the object doesn't corrupt its internal state," then you can achieve this through std::atomic<> for single plain-old-data types that have no invariant between them (a doesn't depend on b) but you need a lock of some sort for any dependent rules you need to enforce.

提交回复
热议问题