user7811169
user7811169

Reputation:

How to read lock a multithreaded C++ program

For the following program multithreaded with openMP, what can I do to prevent other threads reading a "stuff" vector while one thread is writting to "stuff"?

    vector<int> stuff; //Global vector

    void loop() {
    #pragma omp parallel for
       for(int i=0; i < 8000; i++){
          func(i);
       }
    }

    void func(int& i) {
       vector<int> local(stuff.begin() + i, stuff.end()); //Reading and copying global vector "stuff"

       //Random function calls here

    #pragma omp critical
       stuff.assign(otherstuff.begin(), otherstuff.end()); //Writing to global vector "stuff"
    }

Upvotes: 0

Views: 253

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

You can use mutexes to synchronize access to data shared among several threads:

#include <mutex>

std::mutex g_stuff_mutex;

vector<int> stuff; //Global vector

void loop() {
#pragma omp parallel for
   for(int i=0; i < 8000; i++){
      func(i);
   }
}

void func(int& i) {
   g_stuff_mutex.lock();
   vector<int> local(stuff.begin() + i, stuff.end()); //Reading and copying global vector "stuff"
   g_stuff_mutex.unlock();

   //Random function calls here

#pragma omp critical
   g_stuff_mutex.lock();
   stuff.assign(otherstuff.begin(), otherstuff.end()); //Writing to global vector "stuff"
   g_stuff_mutex.unlock();

}

Upvotes: 1

Related Questions