OpenMP将函数的执行分配给线程

OpenMP assign the execution of a function to a thread?

本文关键字:分配 线程 执行 函数 OpenMP      更新时间:2023-10-16

基本上,我需要主线程根据一些全局变量的值继续进行一些操作,这些全局变量可以由辅助线程编辑(以某些选定的间隔)。类似:

vector<int> mySharedVar;
void secondaryThreadFunction() {
   Do some operations
   And update mySharedVar if necessarily  
}
int main() {
 int count = 0;
 while(true) {
    count++;
    if (count%100) {  //> Each 100 iterations run a parallel thraed
      //> RUN secondaryThreadFunction in a separateThread
    }
    this is the main thread that based its operation on mySharedVar
 }
}

secondaryThreadFunction();运行单个并行线程的openmp命令是什么?

还有比这更好的方法吗:

#pragma omp parallel num_threads(2)
    {
        int i = omp_get_thread_num();
        if (i == 0){
            mainThread();
        }
        if (i == 1 || omp_get_num_threads() != 2){
            secondaryThreadFunction();
        }
    }

以下是我的想法:

#include <omp.h>
#include <unistd.h>
#include <vector>
#include <iostream>
std::vector<int> mySharedVar(10);
void secondaryThreadFunction() {
  mySharedVar[5]++;
}
int main() {
  int  i = 0 ;
#pragma omp parallel sections shared(mySharedVar) private(i)
  {
#pragma omp section
    //main thread
    {
      while( mySharedVar[5] < 10) {
        std::cout << "main: ";
        for(i=0; i < mySharedVar.size(); ++i){
          std::cout << mySharedVar[i] << " ";
        }
        std::cout << std::endl;
        usleep(1.e5); // wait 0.1 seconds
      }
    }
#pragma omp section
    {  
      while( mySharedVar[5] < 10) {
        secondaryThreadFunction();  
        usleep(3.e5); // wait 0.3 seconds
      }
    }
  }
}

g++ -fopenmp test_omp_01.cc && ./a.out 编译和运行

输出:

main: 0 0 0 0 0 1 0 0 0 0 
main: 0 0 0 0 0 1 0 0 0 0 
main: 0 0 0 0 0 1 0 0 0 0 
main: 0 0 0 0 0 2 0 0 0 0 
main: 0 0 0 0 0 2 0 0 0 0 
main: 0 0 0 0 0 2 0 0 0 0 
main: 0 0 0 0 0 3 0 0 0 0 
main: 0 0 0 0 0 3 0 0 0 0 
main: 0 0 0 0 0 3 0 0 0 0 
main: 0 0 0 0 0 4 0 0 0 0 
main: 0 0 0 0 0 4 0 0 0 0 
main: 0 0 0 0 0 4 0 0 0 0 
main: 0 0 0 0 0 5 0 0 0 0 
main: 0 0 0 0 0 5 0 0 0 0 
main: 0 0 0 0 0 5 0 0 0 0 
main: 0 0 0 0 0 6 0 0 0 0 
main: 0 0 0 0 0 6 0 0 0 0 
main: 0 0 0 0 0 6 0 0 0 0 
main: 0 0 0 0 0 7 0 0 0 0 
main: 0 0 0 0 0 7 0 0 0 0 
main: 0 0 0 0 0 7 0 0 0 0 
main: 0 0 0 0 0 8 0 0 0 0 
main: 0 0 0 0 0 8 0 0 0 0 
main: 0 0 0 0 0 8 0 0 0 0 
main: 0 0 0 0 0 9 0 0 0 0 
main: 0 0 0 0 0 9 0 0 0 0 
main: 0 0 0 0 0 9 0 0 0 0