2

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

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

哪个是用于运行单个并行线程的 openmp 命令secondaryThreadFunction();

有没有比这更好的方法:

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

1 回答 1

1

这是我想出的:

#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 
于 2012-07-18T10:59:02.290 回答