我有一个遗传算法代码来解决问题。当问题规模变大时,它运行缓慢。所以我有一个想法,使用运行相同GA程序的多线程来加快速度。如何使用C#中调用相同方法的多线程?
但是当我使用4个线程时,它停止发现最佳值太早。我认为这是因为在线程中同时处理相同的变量。但我不知道如何解决这个问题。
所以我想问一下在不同线程中调用包含全局变量的相同方法的正确方法是什么?
我冒出代码,以帮助:
public void Start()
{
CreateInitialPopulation();
Task th1 = new Task(() =>
{
Procedure();
});
Task th2 = new Task(() =>
{
Procedure();
});
Task th3 = new Task(() =>
{
Procedure();
});
Task th4 = new Task(() =>
{
Procedure();
});
th1.Start();
th2.Start();
th3.Start();
th4.Start();
}
#endregion
void Procedure()
{
stopped = false;
while (produced < 10000000)
{
int[] nums = doSelection();
Schedule mother = population[nums[0]];
Schedule father = population[nums[1]];
Schedule child1 = doCrossover(mother, father);
Schedule child2 = doCrossover(father, mother);
doMutation(child1);
doMutation(child2);
population[nums[nums.Length - 1]] = child1;
population[nums[nums.Length - 2]] = child2;
checkBestValueChanged(child1);
checkBestValueChanged(child2);
produced++;
nothingFound++;
if (nothingFound > 300000 && refresh)
{
addNewChromosomes(popSize/10);
nothingFound = 0;
}
Progress = double.Parse((produced * 100d/10000000).ToString("0.00"));
if (stopped)
break;
}
}
UPDATE:此外,当我用lock
整个块algorithym工作不错,但当时它的工作原理是使用一个线程,以正常速度。
变量是全局变量。你要做什么?你至少需要使他们的访问线程安全。 – Nikki9696
另外,线程很难。你确定这是你想要解决这个问题的方式吗? – Nikki9696
@ Nikki9696,例如有一个“最佳”变量,在循环中,如果找到更好的变量,这个变量可以被改变。 –