jeudi 26 février 2015

Is there a way of making atomic shared_ptr in libstd++?

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.


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


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;
}


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


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


Aucun commentaire:

Enregistrer un commentaire