lundi 13 juillet 2020

How to thread-safe function that adds elements to array?

I wrote the following function that accepts an object (element), makes space for it in an existing vector (elements) and updates the vector by adding the new object:

void addElement(const ElementType& element) {
    if (numElements == elements.size()) {
        elements.resize(boost::extents[numElements+1]);
    }

    elements[numElements] = element;

    numElements++;
}

How can I make it thread-safe for MPI? To my understanding, every thread knows what the size of elements is, therefore I don't see why this function would not be thread-safe. numElements is initialized to zero outside this function and is the size of the elements vector.

Edit: I am using the function as written above and mtx lock and unlock as follows, but still the final elements vector contains data from the first rank only.

    #pragma omp parallel for collapse(3) schedule(static)
    for (long n0 = mgr->startN0; n0 < mgr->startN0 + mgr->localN0; n0++) {
      for (int n1 = 0; n1 < Ν; n1++) {
        for (int n2 = 0; n2 < Ν; n2++) {
          ElementType element;
          std::mutex mtx;
            for(int i=0;i<g_field[n0][n1][n2];i++){
              ... do stuff with element ...
              mtx.lock();
              #pragma omp critical
              addElement(element);
              mtx.unlock();}
       }
     }
   }

Aucun commentaire:

Enregistrer un commentaire