gpt4 book ai didi

for-loop - 并行 For 循环

转载 作者:IT王子 更新时间:2023-10-29 01:12:07 31 4
gpt4 key购买 nike

我希望 for 循环使用 go 例程并行。我尝试使用 channel ,但没有用。我的主要问题是,我想在继续之前等待所有迭代完成。这就是为什么在它不起作用之前简单地编写 go 的原因。我尝试使用 channel (我认为是错误的方式)但这让我的代码变得更慢

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
}

最佳答案

所以基本上 goroutine 不应该返回一个值,而是将它插入一个 channel 。如果你想等待所有 goroutines 完成,你可以只计算 goroutines 的数量,或者使用 WaitGroup。在这个例子中,这是一个矫枉过正,因为大小是已知的,但无论如何这是一个很好的做法。这是一个修改后的例子:

package main

import (
"math/rand"
"sync"
)

type Individual struct {
gene []bool
fitness int
}


func createPopulation(populationSize int, individualSize int) []Individual {

// we create a slice with a capacity of populationSize but 0 size
// so we'll avoid extra unneeded allocations
population := make([]Individual, 0, populationSize)

// we create a buffered channel so writing to it won't block while we wait for the waitgroup to finish
ch := make(chan Individual, populationSize)

// we create a waitgroup - basically block until N tasks say they are done
wg := sync.WaitGroup{}

for i := 0; i < populationSize; i++ {

//we add 1 to the wait group - each worker will decrease it back
wg.Add(1)

//now we spawn a goroutine
go createIndividual(individualSize, ch, &wg)
}

// now we wait for everyone to finish - again, not a must.
// you can just receive from the channel N times, and use a timeout or something for safety
wg.Wait()

// we need to close the channel or the following loop will get stuck
close(ch)

// we iterate over the closed channel and receive all data from it
for individual := range ch {

population = append(population, individual)
}
return population

}

func createIndividual(size int, ch chan Individual, wg *sync.WaitGroup) {

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
}
}

// push the population object down the channel
ch <- individual
// let the wait group know we finished
wg.Done()

}

关于for-loop - 并行 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24238820/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com