我希望for循環使用go例程並行。我試圖使用渠道,但沒有奏效。我的主要問題是,我想在繼續之前等待所有迭代完成。這就是爲什麼簡單地在go
之前無效的原因。我試圖用信道(我認爲錯誤的方式),但使我的代碼更慢並行For循環
func createPopulation(populationSize int, individualSize int) []Individual {
population := make([]Individual, populationSize)
//i want this loop to be work parallel
for i := 0; i < len(population); i++ {
population[i] = createIndividual(individualSize)
}
return population
}
func createIndividual(size int) Individual {
var individual = Individual{make([]bool, size), 0}
for i := 0; i < len(individual.gene); i++ {
if rand.Intn(2)%2 == 1 {
individual.gene[i] = true
} else {
individual.gene[i] = false
}
}
return individual
}
我的結構是這樣的:
type Individual struct {
gene []bool
fitness int
}
已經嘗試了不同的版本出來時你設置環境變量GOMAXPROCS? – fabrizioM