1

I am having issues with the following piece of code while using threads.

I read on the Microsoft site that appending to the concurrent_vector does not mess with iterators, so I did not provide and mutex for the duration of the find_if operation.

So the error I am receiving is an "Access violation"

I have 6 threads running concurrently. Should I wrap this in a mutex? Does it need one. I'm fairly new to C++.

std::stringstream key;
key << "SearchString " << ID << ", " << "Options" << ", " << Date;

auto &it = std::find_if(
  m_spList.begin(), m_spList.end(),
  [&key] (std::unique_ptr<IBaseObject>const &bo){
    return bo->ID() == key.str();
  }
);

if (it != m_spList.end()) {
  while (it != m_spList.end()) {
    ReplacePartResult* rpr = dynamic_cast<ReplacePartResult*>(it->get());

    if (rpr) {
      if (rpr->ReplaceItem) {
        replaceBOMID = rpr->BOMID > 0 ? rpr->BOMID : 0;

        if (_parentPart) {
          _parentPart->TemplateBomID = rpr->BOMID;
          _parentPart->Name = rpr->Name;
          _parentPart->Description = rpr->Description;
        }
      }
    }
    it = std::find_if(
      ++it, m_spList.end(),
      [&key](std::unique_ptr<IBaseObject>const &bo){
        return bo->ID() == key.str();
      }
    );
  }
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
muscleman71
  • 91
  • 2
  • 13

1 Answers1

0

Not 100% why, but i re-factored the find_if into a new function and explicitly defined my iterator type and it seems to be behaving. Maybe sening the stringstream into the lambda was the issue?

concurrency::concurrent_vector<std::unique_ptr<IBaseObject>>::iterator IBaseObject_FindKey(concurrency::concurrent_vector<std::unique_ptr<IBaseObject>>& mv, std::string const& _key)
{
    return std::find_if(std::begin(mv), std::end(mv), [&_key](std::unique_ptr<IBaseObject>const &bo){return bo->ID() == _key; });

}
muscleman71
  • 91
  • 2
  • 13