如何读取锁定多线程C ++程序

时间:2017-04-03 22:58:15

标签: c++ multithreading openmp

对于以下使用openMP多线程的程序,我该怎么做才能防止其他线程读取"东西"矢量,而一个线程写入"东西"?

    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"
    }

1 个答案:

答案 0 :(得分:1)

您可以使用互斥锁同步访问多个线程之间共享的数据:

#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();

}