this is my first time working with OpenMP, and I have a beginner knowledge in parallel programming.
What I want to know is how do I do a OpenMP parallel simulation that is synchronized by time?
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:
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? 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.