【发布时间】:2018-10-27 16:10:56
【问题描述】:
我的问题是这样的:
我想用 C++ 中的蚁群优化算法解决 TSP。 现在我已经实现了一个迭代解决这个问题的算法。
例如:我生成了 500 只蚂蚁——它们一个接一个地找到自己的路线。 每只蚂蚁直到前一只蚂蚁完成后才开始。
现在我想并行化整个事情 - 我考虑过使用 OpenMP。
所以我的第一个问题是:我可以生成大量工作的线程吗 同时(蚂蚁数量> 500)?
我已经尝试了一些东西。这是我的 main.cpp 中的代码:
#pragma omp parallel for
for (auto ant = antarmy.begin(); ant != antarmy.end(); ++ant) {
#pragma omp ordered
if (ant->getIterations() < ITERATIONSMAX) {
ant->setNumber(currentAntNumber);
currentAntNumber++;
ant->antRoute();
}
}
这是我的 Ant 类中“关键”的代码,因为每个 Ant 读取和写入同一个矩阵(信息素矩阵):
void Ant::antRoute()
{
this->route.setCity(0, this->getStartIndex());
int nextCity = this->getNextCity(this->getStartIndex());
this->routedistance += this->data->distanceMatrix[this->getStartIndex()][nextCity];
int tempCity;
int i = 2;
this->setProbability(nextCity);
this->setVisited(nextCity);
this->route.setCity(1, nextCity);
updatePheromone(this->getStartIndex(), nextCity, routedistance, 0);
while (this->getVisitedCount() < datacitycount) {
tempCity = nextCity;
nextCity = this->getNextCity(nextCity);
this->setProbability(nextCity);
this->setVisited(nextCity);
this->route.setCity(i, nextCity);
this->routedistance += this->data->distanceMatrix[tempCity][nextCity];
updatePheromone(tempCity, nextCity, routedistance, 0);
i++;
}
this->routedistance += this->data->distanceMatrix[nextCity][this->getStartIndex()];
// updatePheromone(-1, -1, -1, 1);
ShortestDistance(this->routedistance);
this->iterationsshortestpath++;
}
void Ant::updatePheromone(int i, int j, double distance, bool reduce)
{
#pragma omp critical(pheromone)
if (reduce == 1) {
for (int x = 0; x < datacitycount; x++) {
for (int y = 0; y < datacitycount; y++) {
if (REDUCE * this->data->pheromoneMatrix[x][y] < 0)
this->data->pheromoneMatrix[x][y] = 0.0;
else
this->data->pheromoneMatrix[x][y] -= REDUCE * this->data->pheromoneMatrix[x][y];
}
}
}
else {
double currentpheromone = this->data->pheromoneMatrix[i][j];
double updatedpheromone = (1 - PHEROMONEREDUCTION)*currentpheromone + (PHEROMONEDEPOSIT / distance);
if (updatedpheromone < 0.0) {
this->data->pheromoneMatrix[i][j] = 0;
this->data->pheromoneMatrix[j][i] = 0;
}
else {
this->data->pheromoneMatrix[i][j] = updatedpheromone;
this->data->pheromoneMatrix[j][i] = updatedpheromone;
}
}
}
因此,由于某些原因,omp 并行 for 循环无法在这些基于范围的循环上工作。 所以这是我的第二个问题 - 如果你们对如何完成基于范围的循环的代码有任何建议我很高兴。
感谢您的帮助
【问题讨论】:
-
您不需要大于硬件并行化的线程数,即系统上的逻辑 CPU 内核数
标签: c++ multithreading object vector openmp