I have an genetic algorithym code to solve a problem. It works slowly when the problem size gets bigger. So I have an idea to make it faster using multithreads running the same GA procedure.
But when I used 4 threads, it stopped to find best values too early. I think this is because of working on the same variables at the same time in the threads. But I don't know how to solve this.
So I want to ask what is the right way to call the same method that contains global variables in different threads?
My cropped code to help:
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: In addition, when I used lock
for the whole block the algorithym works good but at that time it works like using one thread, at normal speed.