Atomic store throwing error

被刻印的时光 ゝ 提交于 2019-12-14 02:42:14

问题


I recently upgraded to a C++11 compatible compiler, and I was trying to update some code from boost to c++11 standards. I ran into a problem when converting some code using atomic_store over. Here is some simple test code that seems to be throwing a compiler error for me.

int main()
{
    std::shared_ptr<int> m = std::make_shared<int>();
    *m = 1;

    std::shared_ptr<int> a =  std::make_shared<int>();
    *a = 2;

    std::atomic_store(&m,std::move(a));

    std::cout << *m << std::endl;
}

the std::atomic_store(&m,std::move(a)); line is throwing a compiler error for me:

'std::shared_ptr<int>' is not derived from 'volatile std::atomic<_ITp>'
     std::atomic_store(&m,std::move(a));
                                      ^

Has the way atomic_store changed when moving from boost to C++11? Do I now need to create an atomic object of a shared pointer?


回答1:


The following code compiles fine with Clang 3.5:

#include <memory>
int main()
{
    std::shared_ptr<int> foo, bar;
    std::atomic_store(&foo, bar);
}

However, it doesn't compile with GCC 4.9. The above code prints an error message, that atomic_store is not a member of std. If I also include <atomic>, the compiler prints the error message, that is shown in the question.

Apparently, GCC 4.9 does not support atomic operations for std::shared_ptr. See also the documentation of libstdc++:

20.7.2.5 | shared_ptr atomic access | Partial




回答2:


Currently the only safe and viable way to prevent race condition (when smart pointer being copied in one thread is concurrently reset in another) is to always use mutexes when accessing these objects, but that is more expensive than it needs to be, esp. if multiple readers are trying to read the data at roughly the same moment (which is typical in publisher/subscriber model).



来源:https://stackoverflow.com/questions/24618799/atomic-store-throwing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!