简体   繁体   English

我们可以使用 c++20 的 atomic_ref 并发访问用户类型成员 function 吗?

[英]Can we use c++20's atomic_ref to concurrently accessing user type member function?

Consider this problem: I have an atomic_ref of a user type.考虑这个问题:我有一个用户类型的atomic_ref I want to concurrently accessing its member functions.我想同时访问它的成员函数。 See code below:请参见下面的代码:

struct A{
    int counter=0;
    
    int add(){
        ++counter;
        return counter;
    };
};

int main() { 
    A a;
    std::atomic_ref<A> ra{a};
    std::vector<std::thread> v;
    for(int i=0;i<1000;++i){
        v.emplace_back([&ra]{ra.load().add();});
    };
    for(auto & t: v){t.join();};
    std::cout<<a.counter<<std::endl;
 };

Final output is 0 because load() returns a copy.最终 output 为0 ,因为load()返回一个副本。 Is there any other way to reach the correct result by atomic_ref ?有没有其他方法可以通过atomic_ref达到正确的结果?

And I also want to ask that, if we have an atomic_ref<T*> , can we use load() to accessing member functions, eg ra.load()->add() .我还想问一下,如果我们有atomic_ref<T*> ,我们可以使用load()来访问成员函数,例如ra.load()->add() Is it safe?安全吗? Code will become like this:代码会变成这样:

struct A{
    int counter=0;
    
    int add(){
        ++counter;
        return counter;
    };
};

int main() { 
    A* a=new A;
    std::atomic_ref<A*> ra{a};
    std::vector<std::thread> v;
    for(int i=0;i<1000;++i){
        v.emplace_back([&ra]{ra.load()->add();}); //Accessing member functions.
    };
    for(auto & t: v){t.join();};
    std::cout<<a->counter<<std::endl;
 };

In my test, it's indeed 1000 which is correct.在我的测试中,它确实是1000 ,这是正确的。

Atomics are not magical .原子并不神奇 They only affect the loading and accessing of the reference itself, not of anything accessed though the reference.它们只影响引用本身的加载和访问,而不影响通过引用访问的任何内容。

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

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