我有一個遺傳算法代碼來解決問題。當問題規模變大時,它運行緩慢。所以我有一個想法,使用運行相同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,例如有一個「最佳」變量,在循環中,如果找到更好的變量,這個變量可以被改變。 –