'Hoge::v' is not a variable in clause 'shared'
C++でOpemMP並列をする際、
error: 'Hoge::v' is not a variable in clause 'shared'
というエラーが出る事がある。これは、クラスのメンバ変数をshared指定しようとした時のエラー。例えば以下がサンプル。
#include <iostream> #include <omp.h> #include <vector> class Hoge{ private: std::vector<int> v; public: void func(void){ int tid; #pragma omp parallel shared(v) private(tid) { tid = omp_get_thread_num(); #pragma omp critical v.push_back(tid); } for(int i=0;i<v.size();i++){ std::cout << v[i] << std::endl; } }; }; int main(void){ Hoge h; h.func(); }
これをコンパイルすると、
test.cc: In member function 'void Hoge::func()': test.cc:10: error: 'Hoge::v' is not a variable in clause 'shared'
こんなエラーがでる。調べてみたが、どうもクラスのメンバ変数をshared指定できないようなので、一度別のテンポラリ変数を使って後でコピーするしかないらしい。こんな感じ。
#include <iostream> #include <omp.h> #include <vector> class Hoge{ private: std::vector<int> v; public: void func(void){ int tid; std::vector<int> vtmp; #pragma omp parallel shared(vtmp) private(tid) { tid = omp_get_thread_num(); #pragma omp critical vtmp.push_back(tid); } for(int i=0;i<vtmp.size();i++){ v.push_back(vtmp[i]); } for(int i=0;i<v.size();i++){ std::cout << v[i] << std::endl; } }; }; int main(void){ Hoge h; h.func(); }
実行結果。
$ g++ -fopenmp test.cc $ export OMP_NUM_THREADS=4;./a.out 2 1 0 3