本文介绍了有没有一种方法可以在libstd ++中创建atomic shared_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在代码中使用atomic shared_ptr-我有一个单读者,多作者的场景,其中一个小型数据结构将被多个线程复制和覆盖.

I need to use atomic shared_ptr in my code - I have single-reader-multiple-writers scenario where a small data structure will be copied and overwritten by multiple threads.

看到(以及我自己的测试),看来免费原子功能仍然无法使用GCC 4.9.2.

After seeing this and this (and my own tests) it seems that free atomic function still aren't working in GCC 4.9.2.

我试图简单地将shared_ptr放在原子上:

I've tried simply putting shared_ptr in atomic:

#include <atomic>
#include <iostream>
#include <memory>

std::atomic<std::shared_ptr<std::string> > a_var;

void place() {
  std::shared_ptr<std::string> ptr1(new std::string("abc"));
  a_var.store(ptr1);
}

int main(int argc, const char *argv[]) {
  place();
  std::shared_ptr<std::string> ptr2 = a_var.load();
  std::cout<< *ptr2 << std::endl;
  return 0;
}

但是用g++ --std=c++11 -g <filename> -latomic编译后,它会引发段错误.

But after compiling with g++ --std=c++11 -g <filename> -latomic it throws segfault.

似乎正在发生的事情是,在调用store之后,使用复制构造函数创建了一个新的shared_ptr,但是它立即被删除,并且在退出place后释放了ptr1,因此*ptr2抛出了.

What seems to be happening is that after calling store a new shared_ptr is created using a copy constructor, but it's immediately deleted and after exiting place ptr1 is released, so *ptr2 throws.

任何想法如何使其发挥作用

Any ideas how can make it work

推荐答案

std::atomic<.>只能与普通可复制类型"一起使用.

std::atomic<.> can only be used with a 'trivially copyable type'.

std::shared_ptr<std::string>显然不满足这些条件. atomic在某个地方会将对象复制为一块内存,并违反了一个或多个类的某些不变性.

std::shared_ptr<std::string> obviously doesn't satisfy those criteria. Somewhere atomic will be copying the object as a block of memory and violating some invariant of one or more of the classes.

例如,我们都知道:

std::shared_ptr<std::string> s(new std::string("abc"));
std::shared_ptr<std::string> t;
memcpy(&t,&s,sizeof(std::shared_ptr<std::string>));

在副本末尾既可编译又可执行.这也是灾难的保证.

Is both compilable and executable to the end of the copy. It's also a guaranteed recipe for disaster.

在您的情况下,ptr1不知道"已被复制,因此当字符串(ptr1)超出范围时,它将删除该字符串.然后,您访问字符串. 景气.游戏结束.

In your case ptr1 doesn't "know" it's been copied so it deletes the string when it (ptr1) goes out of scope. Then you access the string. Boom. Game Over.

实现您正在执行的操作的标准方法是使用std::mutex保护share_ptr.没有简单的方法来提供指向字符串的无锁指针.这样的对象将引发计算领域的一场革命.

The standard way to achieve what you're doing is to protect the share_ptr with a std::mutex. There is no easy way to provide a lock-free pointer to string. Such an object would usher in a revolution in computing.

这篇关于有没有一种方法可以在libstd ++中创建atomic shared_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:14