简体   繁体   English

C++ OpenMP 并行 for 循环与同步?

[英]C++ OpenMP parallel for loop with synchronization?

this is my first time working with OpenMP, and I have a beginner knowledge in parallel programming.这是我第一次使用 OpenMP,我对并行编程有初步的了解。

What I want to know is how do I do a OpenMP parallel simulation that is synchronized by time?我想知道的是如何进行按时间同步的 OpenMP 并行模拟?

In this simulation, agents would be multithreaded, and they will perform some tasks which could be dependent on each other per loop.在这个模拟中,代理将是多线程的,它们将执行一些每个循环可能相互依赖的任务。

Below is a (unfinished) POC code that is what I am thinking of:以下是我正在考虑的(未完成的)POC代码:

void simulateNext(Agent agent, int time) {
    
  // do simulation stuff

}

int main() {
      // TODO add initialise code for all agents

      int max_time = 10000;
      int num_agents = 1000

      for (int i = 0; i < max_time; i++) {
        #pragma omp parallel for
        for (int j=0; j < num_agents; j++) {
            simulateNext(agents[j], i);
        }
    }

}

I am very sure this will work, however the parallel for does not seem to be the best way to do it, I am guessing that the implementation above means that for every iteration of i?我非常确定这会起作用,但是并行 for 似乎并不是最好的方法,我猜上面的实现意味着对于 i 的每次迭代? I will spawn and destroy threads.我将产生并销毁线程。 That seems like a waste if that is indeed the case.如果确实如此,那似乎是一种浪费。

Is there a better way do this?有更好的方法吗? I was thinking of the following code which could be better but I am not sure it even works.我在想下面的代码可能会更好,但我不确定它是否有效。

int max_time = 10000;

void runSimulation(Agent agent) {
  
  for (int i = 0; i < max_time; i++) {
      // do simulation stuff

      #pragma omp barrier
  }

}

int main() {
      // TODO add initialise code for all agents

      int num_agents = 1000

      #pragma omp parallel for
      for (int j=0; j < num_agents; j++) {
          runSimulation(agents[j]);
      }

}

The simple way to write this is something like this写这个的简单方法是这样的

int main() {
  // TODO add initialise code for all agents
  
  int max_time = 10000;
  int num_agents = 1000
  #pragma omp parallel
  {
    for (int i = 0; i < max_time; i++) {
    #pragma omp for
      for (int j=0; j < num_agents; j++) {
        simulateNext(agents[j], i);
      }
    }
  }
}

There is already an implicit barrier at the end of the omp for , and it is entirely reasonable simply to have each thread execute the outer loop.omp for的末尾已经有一个隐含的屏障,让每个线程执行外部循环是完全合理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM