c++concurrencytbb

Race Condition in tbb::concurrent_vector When Accessing size() in Parallel Node Insertion


I am using tbb::concurrent_vector nodes_ to add multiple nodes to a tree in parallel. The issue arises when I attempt to return nodes_.size(). A race condition occurs when two threads add a node concurrently, causing nodes_.size() to not return the desired outcome.

While I could use a mutex to address this race condition, it would negate the benefits of adding nodes in parallel, making concurrent_vector unnecessary.

Is there a way to continue using concurrent_vector while avoiding race conditions with size()?

Here’s a simplified version of my code, that is run in parallel by multiple threads

int PTree::makeNode(int item) {
  nodes_.push_back(PNode(item));
  return nodes_.size() - 1;
}

Solution

  • In tbb:concurrent_vector using size() to find the position of the last element you inserted is wrong, you cannot do both operations atomically, instead use the returned iterator from push_back()

    int PTree::makeNode(int item) {
      auto it = nodes_.push_back(PNode(item));
      return static_cast<int>(std::distance(nodes_.begin(), it));
    }
    

    godbolt demo