I would like to split a range of numbers into roughly equal size in C using OpenMP. For example, if I have a range from 7 through 24 and number of threads is 8. I would like the first thread to begin from 7 and end at 9. Second thread begin from 10 and end at 12. Third thread begin from 13 and end at 14. Fourth thread begin at 15 and end at 16 and so forth… Until the last thread begins at 23 and ends at 24. The code that I wrote is as follows, but it is not getting the previously explained results. I am wondering if there is something that I missed that I can do or is there a more efficient way of doing this? Your help is greatly appreciated.
Note of predefined declaration of variables based on the example given above:
first = 7
last = 24
size = 2 (which signifies the amount of numbers per thread)
r = 2 (r signifies remainder)
nthreads = 8
myid = is the thread ID in a range of 0 to 7
if (r > 0)
{
if (myid == 0)
{
start = first + myid*size;
end = start + size;
}
else if (myid == nthreads - 1)
{
start = first + myid*size + myid;
end = last;
}
else
{
start = first + myid*size + myid;
end = start + size;
}
}
else
{
start = first + myid*size;
if (myid == nthreads - 1) end = last;
else end = start + size - 1;
}
As far as I remember,
#pragma omp parallel forautomatically divides work between threads in equal chunks, and is ok in most situations.However, if you want to do this manually, here is a piece of code which does what you want:
If there are no additional restrictions, such distribution is indeed optimal.