I'm developing a project and the code is too big. To try to decrease the time spent in a calculation I decided to call this function in parallel.
This worked for some test cases, but for another case the program always hangs, and in others different values are returned at each (wrong) execution.
For the first test case I imagined that I was suffering from deadlock problem (although my function did not block), when I noticed the second case, I came to imagine that the problem was data race .
As I said, initially I will not post all the code of the function I use, because it calls several other functions internally. Also, this method returns an array of float
by reference, so I used std::ref(solucaoNormal)
.
Follow the code:
std::vector<std::vector<float>> solucaoNormal;
std::future<float> threadNormal;
if (isParalel)
threadNormal = std::async(IniciaResolucaoMochila, m, largura, altura, vItensB, std::ref(solucaoNormal));
else
zNormal = IniciaResolucaoMochila(m, largura, altura, vItensB, solucaoNormal);
//faz rotacao dos itens
for (int i = 0; i<itensRotacionados.size(); i++){
aux = itensRotacionados[i].dimensoes[C_Y];
itensRotacionados[i].dimensoes[C_Y] = itensRotacionados[i].dimensoes[C_X];
itensRotacionados[i].dimensoes[C_X] = aux;
}
//resolve a mochila com os itens rotacionados
zRot = IniciaResolucaoMochila(m, largura, altura, itensRotacionados, solucaoRot);
solucaoRot[m + 2][0] = 2;
if (isParalel)
zNormal = threadNormal.get();
Function Header:
float MochilaBidimensional::IniciaResolucaoMochila(int m, int largura, int altura, vectorBd vItensB, matrix &solucaoMochila);
Ah yes, this code runs several times.