i want to write a copyOnwrite thread-safe vector like below, if i not use weak_ptr, it works fine. it seems shared_ptr reset call vector copy constructor and then weak_ptr's. the weak_ptr ctor not behaves as expect..
so how can i fix this issue.. my code just like below
class B {
public:
void print() {
}
};
class A {
typedef std::vector<std::weak_ptr<B>> TargetList;
std::shared_ptr<TargetList> _targets;
std::mutex _targetsMutex;
public:
A() {
_targets = std::make_shared<TargetList>();
}
void addTarget(std::shared_ptr<B> newTarget) {
std::lock_guard<std::mutex> lock(_targetsMutex);
if (!_targets.unique()) {
_targets.reset(new TargetList(*_targets));
}
assert(_targets.unique());
_targets->push_back(newTarget);
}
void traverse() {
std::shared_ptr<TargetList> targets;
{
std::lock_guard<std::mutex> lock(_targetsMutex);
targets = _targets;
assert(!_targets.unique());
}
assert(!targets.unique());
for ( auto & it : *targets) {
auto outp = it.lock();
if(outp) {
outp->print();
}
}
}
};
some kind of test code here..
static void spawnB(A *a) {
std::shared_ptr<B> b[20000];
for (int i = 100; i< 20000; i++) {
b[i] = std::make_shared<B>();
a->addTarget(b[i]);
}
std::cout<<a->getCount()<<std::endl;
}
int main() {
A *a = new A();
std::shared_ptr<B> b = std::make_shared<B>();
a->addTarget(b);
std::thread t1(&spawnB, a);
std::thread t2(&A::traverse1000, a);
b.reset();
t1.join();
t2.join();
delete a;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire