In C++ I would like two for loops to execute at the same time and not have one wait for the other one to go first or wait for it to end.
I would like the two for loops (or more) to finish the loops in the same speed it would take one loop of the same size to finish.
I know it's been asked and answered, but not in an example this simple. I'm hoping to solve this specific problem. I worked combinations of pragma omp code examples and couldn't get the result.
#include <iostream>
using namespace std;
#define N 5
int main(void) {
int i;
for (i = 0; i < N; i++) {
cout << "This is line ONE \n";
};
#pragma omp parallel
#pragma omp for
for (i = 0; i < N; i++) {
cout << "This is line TWO \n";
};
};
Compiling
$ g++ parallel.cpp -fopenmp && ./a.out
The output of the code is this, in the time it takes to run two loops...
This is line ONE
This is line ONE
This is line ONE
This is line ONE
This is line ONE
This is line TWO
This is line TWO
This is line TWO
This is line TWO
This is line TWO
The output I would like is this They don't have to print one after the other like this, but I would think they would if they were both getting to the print part of the loops at the same times. What I really need is for the loops to start and finish at the same time (with the loops being equal).
This is line ONE
This is line TWO
This is line ONE
This is line TWO
This is line ONE
This is line TWO
This is line ONE
This is line TWO
This is line ONE
This is line TWO
There's this Q&A here, but I don't quite understand the undeclared foo and the //do stuff with item parts. What kinda stuff? What item? I have not been able to extrapolate from examples online to make what I need happen.
cout << "This is line ONE \n"; cout << "This is line TWO \n";in a single loop, it would get you exactly the desired output.#pragma omp parallelwork backwards on loops that have already finished?coutuse a lock internally to prevent any data race so it cannot run truly in parallel. The same thing apply forprintf(and certainly all similar functions). You appear not to need parallelism but concurrency which is totally different. You can do concurrency with multiple threads but synchronizing at fine grain is clearly not efficient on modern hardware (unless the two threads run in the same core in separate hardware threads. OpenMP appears not to be the good tool here: it does not provides concurrency features (although they can be emulated).