Altering Loop Variables in C++

General OpenMP discussion

Altering Loop Variables in C++

Postby jburr » Tue Nov 01, 2011 3:02 pm

I'm a beginner at parallel programming. How might I achieve the following affect using OpenMP? Altering the loop variable appears to cause big issues. Just for example's sake, consider a loop that acts upon even numbers only.

Code: Select all
#pragma omp parallel for
for(int i=0; i < reallyBigNumber; i=i+2)


Bad things happened. My code would spit back incorrect solutions. So I considered something like this:
Code: Select all
#pragma omp parallel for
for(int i=0; i < reallyBigNumber; i++)
   if(i % 2 == 0)
      // do a ton of work


Is this the only way to achieve this affect? I'm not real versed on the inner workings of all this. Would there be any issues as far as one processor getting all the threads that do work and one processor getting all the threads that essentially do nothing? (i.e. when using a multi-core processor, is a queue of threads formed where processors just grab the next available thread needing work?) Essentially, I want to avoid something like this:
Processor 1 gets i=0, does a ton of work.
Processor 2 gets i=1, does nothing.
Processor 1 gets i=2, does a ton of work.
Processor 2 gets i=3, and again does absolutely nothing.
...

I suppose the behavior I want would be like this:
Processor 1 gets i=0, does a ton of work.
Processor 2 gets i=1, does nothing.
Processor 2 gets i=2, does a ton of work.
Processor 1 gets i=3, does nothing.
Processor 1 gets i=4, does a ton of work.
...

My goal here is to fully utilize all processors to significantly cut down on the run time of an algorithm. And can someone explain what is happening with the #pragma omp parallel for loop? I would only assume a new thread gets created for every iteration of the for loop. And thus, small loops would probably be more time demanding because of the time involved in setting up that thread? Or am I way off base here?

Thanks in advance.
jburr
 
Posts: 1
Joined: Tue Nov 01, 2011 2:36 pm

Re: Altering Loop Variables in C++

Postby ftinetti » Mon Nov 07, 2011 4:59 am

Hi,

As far as I can see, the loop looks ok to be parallelizable via the omp parallel for directive according to the spec 3.0.

I think the problem is inside the loop, i.e. race conditions, maybe if you send a runnable reduced example to play with we could see something else.

HTH.
ftinetti
 
Posts: 575
Joined: Wed Feb 10, 2010 2:44 pm


Return to Using OpenMP

Who is online

Users browsing this forum: No registered users and 8 guests