I have a while
loop and want to parallelize it on 2 threads using OpenMP. Variables inside the loop don't depend on their values from previous iteration, so I figured there has to be some way of parallelizing it. I have 2 threads, so there could be 2 iterations of while loop happening simultaneously each time with each loop performing their own calculations. Goal of this loop is to find the value of alfa
, which is a step size in conjugate gradient method for finding optimal point.
I guess I have to somehow utilize alfa
, alfaIter
variables and OpenMP statements to make this parallel loop work, but have no idea how.
#pragma omp parallel num_threads(2)
{
while (alfaSet == false) {
alfaIter++;
alfa = pow(gamma, alfaIter - 1);
b = 0;
for (i = 0; i < dim; i++) {
testX[i] = x[i] + alfa * d[i];
}
for (i = 0; i < dim; i++) {
b += d[i] * g[i];
}
if (shanno(testX, dim) - shanno(x, dim) <= delta * alfa * b) {
alfaIter = 0;
alfaSet = true;
}
}
}
EDIT 1: This implementation seems ok:
#pragma omp parallel num_threads(alfaThreads)
{
int alfaIter = omp_get_num_threads();
int step = omp_get_num_threads();
double localAlfa = alfa;
double *testX = (double *) malloc(dim * sizeof(double));
while (!alfaSet) {
#pragma omp barrier
alfaIter += step;
localAlfa = pow(gamma, alfaIter - 1);
for (i = 0; i < dim; i++) {
testX[i] = x[i] + localAlfa * d[i];
}
if (func(testX, dim) - delta * localAlfa * b <= oldFunc) {
#pragma omp critical
{
if (!alfaSet) {
alfaSet = true;
alfaIter = 0;
alfa = localAlfa;
}
}
}
}
free(testX);
}
So after playing with this code for a while I figured there wasn't any synchronization, so threads didn't wait for each other and they reached parts of code in a unpredictable manner. OpenMP barrier syncs them now and I always get the same number of iterations plus performance gain. However, sometimes program crashes now. Deadlocks? How to check what causes the crash and how to prevent it?
Here is the whole implementation of algorithm: https://gist.github.com/mazury/394adc82ab51ce36acfae297ae0555ce